通用存储库:
public class EFRepository<T> where T : class
{
private DbContext _context;
public EFRepository(DbContext context)
{
this._context = context;
}
public void Insert(T entity)
{
this._context.Entry<T>(entity).State = EntityState.Added;
}
public bool Commit()
{
return this._context.SaveChanges() > 0;
}
}
领域模型:
public class BaseEntity
{
public string BaseEntityProp1 { get; set; }
public string BaseEntityProp2 { get; set; }
}
public class Entity1 : BaseEntity
{
public int Entity1ID { get; set; }
}
public class Entity2 : BaseEntity
{
public int Entity2ID { get; set; }
}
每混凝土表 (TPC) 映射:
public class Entity1Map : EntityTypeConfiguration<Entity1>
{
public Entity1Map()
{
this.HasKey(e => e.Entity1ID);
this.Property(e => e.Entity1ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Map(m =>
{
m.ToTable("Entity1");
m.MapInheritedProperties();
});
}
}
public class Entity2Map : EntityTypeConfiguration<Entity2>
{
public Entity2Map()
{
this.HasKey(e => e.Entity2ID);
this.Property(e=> e.Entity2ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Map(m =>
{
m.ToTable("Entity2");
m.MapInheritedProperties();
});
}
}
语境 :
public class MyContext : DbContext
{
public MyContext()
{
}
public DbSet<Entity1> Entities1{ get; set; }
public DbSet<Entity2> Entities2 { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Entity1Map());
modelBuilder.Configurations.Add(new Entity2Map());
base.OnModelCreating(modelBuilder);
}
}
样本数据 :
EFRepository<BaseEntity> baseRepository = new EFRepository<BaseEntity>(new MyContext ());
List<BaseEntity> entities = new List<BaseEntity>()
{
new Entity1()
{
BaseEntityProp1 = "Entity1Prop1",
BaseEntityProp2 = "Entity1Prop2",
},
new Entity2()
{
BaseEntityProp1 = "Entity2Prop1",
BaseEntityProp2 = "Entity2Prop2",
}
};
foreach (var entity in entities)
{
baseRepository.Insert(entity);
baseRepository.Commit();
}