0

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!

1
  • 1
    DbContext already contains a generic method Set<T>(), you can call that directly as it is public. Example: var allUsers = contextInstance.Set<User>().ToList(); Is that what you are looking for? Commented Jan 7, 2020 at 19:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.