0

My DbContext code is similar to this:

public class MyDbContext : DbContext, IMyDbContext
{
   public DbSet<Customer> Customers { get; set; }
   public DbSet<Product> Products { get; set; }
  ...
}

And I want to add dbsets in dbcontext dinamically, with a code similar to this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    var baseAssemblyName = "Namespace.Web.Model";
    var assemblyType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.Equals(baseAssemblyName));

    //Culture is a class defined in the assembly where my Entity models reside
    var typesToRegister = assemblyType.GetTypes()
        .Where(type => type.Namespace != null && type.Namespace.Equals(baseAssemblyName))
        .Where(type => type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>));

    foreach (var type in typesToRegister)
    {
        dynamic configurationInstance = Activator.CreateInstance(type);
        modelBuilder.Configurations.Add(configurationInstance);
    }
}

But it is not executing, I put a breakpoint in the beggining of this method and at that point there are building errors in the repository layer that uses for example:

public ICustomer Get(int id)
{
    return db.Customers.Find(id);
}

What can i do for create dinamically the entities in dbcontext?

Thanks!

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
vicky_864
  • 57
  • 8
  • What build errors? And where exactly? Is the error you're getting saying something like `... does not contain a definition for '...'`? – bassfader Jul 25 '17 at 12:46
  • This is the error that i get: Error CS1061 'IMyDbContext' does not contain a definition for 'Customers' and no extension method 'Customers' accepting a first argument of type 'IMyDbContext' could be found (are you missing a using directive or an assembly reference?) MyProject.Web.DataAccess – vicky_864 Jul 25 '17 at 13:40

1 Answers1

1

In this case, you should use Dbset like this.

public ICustomer Get(int id)
{
   return db.Set<Customer>().Find(id);
}
severus_92
  • 88
  • 5