[英]Entity Framework code first adding DbSet property
I just started working with Entity Framework 6.1.2.我刚刚开始使用 Entity Framework 6.1.2。 I am using code first migration.
我正在使用代码优先迁移。 I have around 78 entities in database.
我在数据库中有大约 78 个实体。 My question is that is there any way we can make the DbSet property generic in DatabaseContext class so I don't have to define all 78 properties?
我的问题是有什么方法可以使 DatabaseContext 类中的 DbSet 属性通用,这样我就不必定义所有 78 个属性? For example
例如
public class DatabseDbContext : DbContext
{
public DbSet<Users> Users { get; set; }
public DbSet<Roles> Roles { get; set; }
public DbSet<Models> Models { get; set; }
public DbSet<Rights> Rights { get; set; }
}
I don't want to make all these properties.我不想制作所有这些属性。 Instead I want one generic property or function to return the DbSet of respective type.
相反,我想要一个通用属性或函数来返回相应类型的 DbSet。 Thanks in advance!
提前致谢!
Yes you can.是的你可以。 But you really shouldn't.
但你真的不应该。
You can register entity types in OnModelCreating
without having a DbSet<T>
.您可以在
OnModelCreating
注册实体类型而无需DbSet<T>
。 EG:例如:
class Db : DbContext
{
public Db(string constr) : base(constr) { }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entityTypes = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.Namespace == "MyApp.Entities");
foreach (var entityType in entityTypes)
{
modelBuilder.RegisterEntityType(entityType);
}
base.OnModelCreating(modelBuilder);
}
}
But you'll always have to access the Entities through DbContext.Set .但是您始终必须通过DbContext.Set访问实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.