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

后端 未结 4 755
死守一世寂寞
死守一世寂寞 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 GetIQueryableByTableName(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;
        }
    

提交回复
热议问题