当我有实体时,在DbContext中动态查找指定的通用DbSet [英] Find a specified generic DbSet in a DbContext dynamically when I have an entity
本文介绍了当我有实体时,在DbContext中动态查找指定的通用DbSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程和 DbContext
:
public class Order:BaseEntity
{
public Number {get; set;}
}
Product:BaseEntity;
{
public Name {get; set;}
}
public class Context : DbContext
{
....
public DbSet<Order> Orders { set; get; }
public DbSet<Product> Products { set; get; }
....
}
我有一个对象列表我也想添加到上下文中,但是我不知道如何动态地根据每种实体类型找到合适的通用 DbSet
。
I have a list of objects that want to add to my context, too, but I don't know how can I find appropriate generic DbSet
according each entity type dynamically.
IList<BaseEntity> list = new List<BaseEntity>();
Order o1 = new Order();
o1.Numner = "Ord1";
list.Add(o1);
Product p1 = new Product();
p1.Name = "Pencil";
list.Add(p1);
Context cntx = new Context();
foreach (BaseEntity entity in list)
{
cntx.Set<?>().Add(entity);
}
我该怎么做?
推荐答案
DbContext
有一个名为 Set
的方法,可以用来获取非通用的 DbSet
,例如:
DbContext
has a method called Set
, that you can use to get a non-generic DbSet
, such as:
var someDbSet = this.Set(typeof(SomeEntity));
所以在您的情况下:
foreach (BaseEntity entity in list)
{
cntx.Set(entity.GetType()).Add(entity);
}
这篇关于当我有实体时,在DbContext中动态查找指定的通用DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文