I have following classes and 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; }
....
}
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);
}
How can I do that?
The question does not specify EF version and the proposed answer does not work anymore for Entity Framework Core (DbContext does not have non-generic set method in EF core at least at the date of this answer).
Yet you can still have a working extension method using the answer of Jon Skeet to this question. My code is added below for convenience.
**Update: Added the generic function call as well returning IQueryable< T> thanks to comment from Shaddix.
DbContext
has a method calledSet
, that you can use to get a non-genericDbSet
, such as:So in your case:
In addition to Pablo answer:
You can add a class to your project:
This class add a Extention method
AsEnumerable
toDbSet
instance and when you want to use it for example for Count or filter some row: