猿问

EF CodeFirst-获取所有实体

我有下一个上下文:


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; }

}

是否存在获取我的上下文的所有实体的任何方法?这样的东西MyContext.GetAllEntities()会回来{Customer, Provider, Product}。


慕斯王
浏览 264回答 2
2回答

不负相思意

在代码中,您可以在所有DbSet上调用ToList()。否则,您将不得不编写一个执行a的存储过程,UNION然后仅调用sp。public List<object> GetAllEntities(MyContext db){&nbsp; &nbsp; var results = new List<object>();&nbsp; &nbsp; results.AddRange(db.Customers.ToList());&nbsp; &nbsp; results.AddRange(db.Providers.ToList());&nbsp; &nbsp; results.AddRange(db.Products.ToList());&nbsp; &nbsp; return results;}编辑: 好的无名列表,然后使用反射。MyContext db = new MyContext();var resultsList = new List<object>();PropertyInfo[] info = db.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);foreach(PropertyInfo item in info){&nbsp; &nbsp;//Check for array, that it is a DbSet etc...&nbsp; &nbsp;var setType = item.PropertyType.GetTypeInfo().GenericTypeArguments[0];&nbsp; &nbsp;resultsList.AddRange(db.Set(setType).ToListAsync().Result);}return resultsList;

慕的地10843

根据Wurd的回复:private IEnumerable<Type> GetAllEntities (){&nbsp; &nbsp;var entities = new List<Type> ();&nbsp; &nbsp;PropertyInfo[] info = GetType ().GetProperties (BindingFlags.Public | BindingFlags.Instance);&nbsp; &nbsp;foreach (PropertyInfo item in info) {&nbsp; &nbsp; &nbsp; var setType = item.PropertyType.GetTypeInfo ().GenericTypeArguments[0];&nbsp; &nbsp; &nbsp; entities.Add (setType);&nbsp; &nbsp;}&nbsp; &nbsp;return entities;}
随时随地看视频慕课网APP
我要回答