C# EF CodeFirst-获取所有实体
我有下一个背景:C# EF CodeFirst-获取所有实体,c#,entity-framework,C#,Entity Framework,我有下一个背景: 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; } } 公共类MyContex
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:DbContext
{
公共虚拟数据库集客户{get;set;}
公共虚拟数据库集提供程序{get;set;}
公共虚拟数据库集产品{get;set;}
}
是否存在获取我的上下文的所有实体的方法?
类似于MyContext.getAllenties()
的东西,返回{Customer,Provider,Product}
编辑
我想在OnModelCreating
中检索实体,以便在用自定义属性修饰的确定属性中创建索引。
在OnModelCreating
上,我无法访问上下文,它在本文中是如何解释的
谢谢 在代码中,您可以在所有数据库集上调用ToList()。否则,您必须编写一个执行
联合的存储过程,只需调用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;
}
公共列表getAllenties(MyContext数据库)
{
var results=新列表();
results.AddRange(db.Customers.ToList());
results.AddRange(db.Providers.ToList());
results.AddRange(db.Products.ToList());
返回结果;
}
编辑:
对于无名列表,可以使用反射
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;
MyContext db=newmycontext();
var resultsList=新列表();
PropertyInfo[]info=db.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(信息中的PropertyInfo项)
{
//检查数组,确认它是一个DbSet等。。。
var setType=item.PropertyType.GetTypeInfo().GenericTypeArguments[0];
resultsList.AddRange(db.Set(setType).ToListSync().Result);
}
返回结果列表;
基于以下人员的响应:
private IEnumerable GetAllenties()
{
var entities=新列表();
PropertyInfo[]info=GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach(信息中的PropertyInfo项){
var setType=item.PropertyType.GetTypeInfo().GenericTypeArguments[0];
添加(setType);
}
返回实体;
}
OP的可能重复并不意味着通过实体名称获取数据。
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;
}