简体   繁体   English

实体框架代码首先添加 DbSet 属性

[英]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.

相关问题 添加到包含列表的类的dbset时,实体框架代码首先出现NullReferenceException - Entity Framework Code First NullReferenceException when adding to a dbset of class that contains a list 宣布DBSet <Type> 在DBcontext中 - 实体框架代码优先 - Declaring DBSet<Type> within DBcontext - Entity Framework Code First 首先使用Entity Framework 4代码在DbContext.DbSet中插入等效的InsertOnSubmit - InsertOnSubmit equivalent in DbContext.DbSet using Entity Framework 4 code first Code-First:将实体添加到dbset时的空引用异常 - Code-First: Null reference exception when adding an entity to a dbset 在Entity Framework Code First中添加关联实体计数的属性 - Adding a property for the count of associated entities in Entity Framework Code First 在实体框架中使用DbSet <TEntity> .Local属性 - Using DbSet<TEntity>.Local Property in Entity Framework 使用包含条件的实体代码第一个DbSet - Entity Code First DbSet using include with conditions Entity Framework 5 代码先添加图片 - Entity Framework 5 Code first adding an image 实体框架代码首先添加记录错误 - Entity Framework Code First adding record error 代码优先实体框架添加对象 - Code First Entity Framework Adding Object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM