public AdminDbContext() : base("MemberDbContext") { //不使用代理创建导航属性,避免WCF序列化错误 Configuration.ProxyCreationEnabled = false; //Configuration.LazyLoadingEnabled = false; } public DbSet<Employee> Employees { get; set; } public DbSet<Role> Roles { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Configurations.Add(new EmployeeMap()); modelBuilder.Configurations.Add(new RoleMap()); base.OnModelCreating(modelBuilder); } public int Commit() { return base.SaveChanges(); }
public class EmployeeMap : EntityTypeConfiguration<Employee> { ...... }
protected override void OnModelCreating(DbModelBuilder modelBuilder) { var typesToRegister = Assembly.GetExecutingAssembly().GetTypes() .Where(type => !String.IsNullOrEmpty(type.Namespace)) .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration<>)); foreach (var type in typesToRegister) { dynamic configurationInstance = Activator.CreateInstance(type); modelBuilder.Configurations.Add(configurationInstance); } //...or do it manually below. For example, //modelBuilder.Configurations.Add(new LanguageMap()); base.OnModelCreating(modelBuilder); }