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
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>;
}
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>>();
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.
replace
nonGeneric.Cast<IUser>();
by
Enumerable.Cast<IUser>(nonGeneric);