[英]How to pass an string as a type parameter for a generic DbSet in Entity Framework?
考慮以下示例代碼,將C#泛型類型作為參數傳遞的最簡潔方法是什么?
public dynamic MyDbSet(string typeName)
{
var typeofDbSet = typeof(DbSet<>);
Type[] typeArgs = { Type.GetType(typeName) };
var type = typeofDbSet.MakeGenericType(typeArgs);
dynamic dbsetOfT = Activator.CreateInstance(type);
return dbsetOfT;
//Call it
//var notificationTypes = MyDbSet("NotificationType");
//var list = notificationTypes.ToList();
}
或類似這樣的東西:
public dynamic MyDbSet2(string typeName)
{
var keyValuePairs = new Dictionary<string, dynamic>
{
{nameof(NotificationType), Set<NotificationType>().AsQueryable()}
};
return keyValuePairs[typeName];
//Call it
//var notificationTypes = MyDbSet2("NotificationType");
//var list = notificationTypes.ToList();
}
Activator.CreateInstance(type)
將失敗,因為DbSet
沒有公共的無參數構造函數。
除非您確實需要將類型名稱作為字符串傳遞,否則執行此操作的最佳方法是創建泛型函數,獲取構造函數並調用它。 會是這樣的:
public DbSet<T> MyDbSet<T>() where T : class
{
return (DbSet<T>)typeof(DbSet<T>).GetConstructor(BindingFlags.NonPublic |
BindingFlags.Instance, null, Type.EmptyTypes, null).Invoke(null);
}
然后,您可以通過MyDbSet<NotificationType>()
調用
更新:
由於需要傳遞名稱,因此您可以執行以下操作:
public dynamic MyDbSet(string typeName)
{
return typeof(DbSet<>).MakeGenericType(Type.GetType(typeName)).
GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance,
null, Type.EmptyTypes, null).Invoke(null);
}
然后,可以通過MyDbSet("<namespace>.NotificationType")
調用。 指定名稱空間是必需的,因為否則Type.GetType
將找不到類型並返回null
嘗試以下擴展代碼:
//Use var list = _context.MyDbSet("ConsoleAppEF.Student").ToList();
public static IQueryable MySet(this SchoolContext context, string typeName)
{
var T = Type.GetType(typeName);
// Get the generic type definition
MethodInfo method = typeof(SchoolContext)
.GetMethod("MySet", BindingFlags.Public | BindingFlags.Instance);
// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(T);
return method.Invoke(context, null) as IQueryable;
}
public static IQueryable<T> Set<T>(this SchoolContext context)
{
// Get the generic type definition
MethodInfo method = typeof(SchoolContext)
.GetMethod(nameof(SchoolContext.Set), BindingFlags.Public | BindingFlags.Instance);
// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(typeof(T));
return method.Invoke(context, null) as IQueryable<T>;
}
public static IList ToList1(this IQueryable query)
{
var genericToList = typeof(Enumerable).GetMethod("ToList")
.MakeGenericMethod(new Type[] { query.ElementType });
return (IList)genericToList.Invoke(null, new[] { query });
}
樣本DbContext:
public class SchoolContext : DbContext
{
public SchoolContext() : base("SchoolContext")
{
}
public DbSet<Student> Students { get; set; }
public virtual new DbSet<TEntity> MySet<TEntity>() where TEntity : BaseEntity
{
return base.Set<TEntity>();
}
}
樣本實體:
public class Student : BaseEntity
{
public string LastName { get; set; }
public string FirstMidName { get; set; }
}
public class BaseEntity
{
public int Id { get; set; }
}
用它:
class Program
{
static void Main(string[] args)
{
Seed();
var _context = new SchoolContext();
var list = _context.MySet("ConsoleAppEF.Student").ToList1();
}
private static void Seed()
{
var _context = new SchoolContext();
var students = new List<Student>
{
new Student{FirstMidName="Carson",LastName="Alexander"},
};
students.ForEach(s => _context.Students.Add(s));
_context.SaveChanges();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.