Ravindra Zemse
Ravindra Zemse

Reputation: 23

Entity Framework code first adding DbSet property

I just started working with Entity Framework 6.1.2. I am using code first migration. I have around 78 entities in database. 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? 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. Thanks in advance!

Upvotes: 0

Views: 556

Answers (1)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 89091

Yes you can. But you really shouldn't.

You can register entity types in OnModelCreating without having a 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.

Upvotes: 2

Related Questions