我的DbContext代码与此类似:
public class MyDbContext : DbContext, IMyDbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Product> Products { get; set; }
...
}
我想在dbcontext中添加dbsets,其代码类似于:
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);
}
}
但它没有执行,我在此方法的开头设置了一个断点,此时在存储库层中存在构建错误,例如:
public ICustomer Get(int id)
{
return db.Customers.Find(id);
}
我可以做什么来创建dbcontext中的实体?
谢谢!
答案 0 :(得分:1)
在这种情况下,您应该像这样使用Dbset。
public ICustomer Get(int id)
{
return db.Set<Customer>().Find(id);
}