1

我有一段代码使用 EF 将记录插入数据库。我想使用相同的代码插入 5 个不同的表。唯一的区别是表名和单个列名。如何构造代码块,以便根据对象类型插入正确的表中?

当前代码块:

if (entity is Fruit)
{
    FruitLink link = new FruitLink()
    {
       FruitLinkId = // some number,
       // Other properties
    }
    context.FruitLinks.Add(link);
    context.SaveChanges();
}

我的目标不是为if( entity is Fruit )我要插入的每种不同类型都有一个语句。唯一会根据实体类型改变的是表名(即 FruitLink)和主键名(即 FruitLinkId)。

4

1 回答 1

0

通用存储库:

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();
}
于 2013-09-23T06:41:58.250 回答