1

I've the next context:

public class MyContext : DbContext
{
   public virtual DbSet<Customer> Customers { get; set; }
   public virtual DbSet<Provider> Providers { get; set; }
   public virtual DbSet<Product> Products { get; set; }
}

Exists any method to get all entities of my context? Something like MyContext.GetAllEntities() that returns {Customer, Provider, Product}.

EDIT I want retrieve the entities in OnModelCreating for creating indexes in determinated properties that are decorated with custom attribute. On OnModelCreating I can not access to the context how it's explains in this question

Thanks!

Rafael León
  • 71
  • 1
  • 9
  • Possible duplicate of [how to get a list of all entities in EF 5?](https://stackoverflow.com/questions/21182716/how-to-get-a-list-of-all-entities-in-ef-5) – CodeNotFound May 02 '18 at 16:06

2 Answers2

0

In code you can call ToList() on all your DbSets. Otherwise you would have to write a stored procedure that does a UNION and just call the sp.

public List<object> GetAllEntities(MyContext db)
{
    var results = new List<object>();
    results.AddRange(db.Customers.ToList());
    results.AddRange(db.Providers.ToList());
    results.AddRange(db.Products.ToList());

    return results;
}

EDIT: Fine for nameless list, use reflection then.

MyContext db = new MyContext();
var resultsList = new List<object>();

PropertyInfo[] info = db.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(PropertyInfo item in info)
{
   //Check for array, that it is a DbSet etc...
   var setType = item.PropertyType.GetTypeInfo().GenericTypeArguments[0];

   resultsList.AddRange(db.Set(setType).ToListAsync().Result);
}

return resultsList;
Wurd
  • 465
  • 2
  • 15
0

Based on the response from Wurd:

private IEnumerable<Type> GetAllEntities ()
{
   var entities = new List<Type> ();
   PropertyInfo[] info = GetType ().GetProperties (BindingFlags.Public | BindingFlags.Instance);
   foreach (PropertyInfo item in info) {
      var setType = item.PropertyType.GetTypeInfo ().GenericTypeArguments[0];
      entities.Add (setType);
   }
   return entities;
}
Rafael León
  • 71
  • 1
  • 9