Search code examples
c#entity-frameworkgenericscode-firstdbset

Find a specified generic DbSet in a DbContext dynamically when I have an entity


I have following classes and DbContext:

public class Order : BaseEntity
{
    public Number {get; set;}
}
public class 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?


Solution

  • DbContext has a method called Set, that you can use to get a non-generic DbSet, such as:

    var someDbSet = this.Set(typeof(SomeEntity));
    

    So in your case:

    foreach (BaseEntity entity in list)
    {
          cntx.Set(entity.GetType()).Add(entity);         
    }