DbSet.Cast() Error: Cannot create a DbSet from a non-generic DbSet for objects of type 'Entity'

后端 未结 4 724
死守一世寂寞
死守一世寂寞 2021-01-02 15:22

Version Info:

I am using C# 4.5, Entity Framework 6.0, and MEF.

Code and Unit Test

I created a Test Project to expl

相关标签:
4条回答
  • 2021-01-02 15:54

    As I wasn't able to cast a generic DbSet to a typed DbSet I used instead a typed IQueryable which can do the same things I needed from the DbSet.

    Here is a extension that can get you that:

        public static IQueryable<T> GetIQueryableByTableName<T>(this DbContext context, string tableName)
        {
            var type = Assembly.GetExecutingAssembly().GetTypes().FirstOrDefault(t => t.Name == tableName);
            if (type == null)
            {
                throw new Exception("GetIQueryableByTableName received an invalid table name.");
            }
            return context.GetType().GetMethod("Set", new Type[0]).MakeGenericMethod(type).Invoke(context, new object[0]) as IQueryable<T>;
        }
    
    0 讨论(0)
  • 2021-01-02 16:15

    Ok i know nothing about Entity framework but from looking at the docs

    http://msdn.microsoft.com/en-us/library/gg696521%28v=vs.103%29.aspx

    DbSet<TEntity> item = DbContext.Set<TEntity>;
    

    so actually your code would be the same as this:

    DbSet<User> nonGeneric = context.Set<User>();
    

    and to get a IUser

    DbSet<IUser> nonGeneric = context.Set<User>();
    

    or maybe

    var generic = nonGeneric.Cast<DbSet<IUser>>();
    
    0 讨论(0)
  • 2021-01-02 16:16

    For this, I would actually suggest using reflection. In the constructor of your DbContext, you can set a property to the function pointer:

    method = this.GetType().GetMethod("Set", new Type[0]).MakeGenericMethod(typeof(UserImplementation));
    

    You can then invoke this using:

    method.Invoke(this, new object[0]);
    

    And this should return an object of type DbSet<UserImplementation> which the .Cast<>() method can then be invoked on.

    0 讨论(0)
  • 2021-01-02 16:16

    replace

    nonGeneric.Cast<IUser>();
    

    by

    Enumerable.Cast<IUser>(nonGeneric);
    
    0 讨论(0)
提交回复
热议问题