我有两个实体(表)Action和ActionLog。 ActionLog源自Action。我需要在单独使用时将实体Action映射到表Action,并在继承关系中使用它时将其映射到表ActionLog。
动作实体属性:
ActionLog实体属性:
操作表列:
ActionLog表格列:
这是否可以在单个上下文中使用EF6 Code First映射?
我试着更明确。我需要这样的东西:
using(var ctx = new DbContext())
{
var action = new Action
{
Action_Property1 = 1,
Action_Property2 = 2,
Action_Property3 = 3
};
ctx.Actions.Add(action);
ctx.SaveChanges();
}
上面的行应该将Action实体写入Action表。
using(var ctx = new DbContext())
{
var actionLog = new ActionLog
{
Action_Property1 = 1,
Action_Property2 = 2,
Action_Property3 = 3,
ActionLog_Property1 = 1
};
ctx.ActionLogs.Add(actionLog);
ctx.SaveChanges();
}
上面的行应该将ActionLog实体写入ActionLog表。
答案 0 :(得分:1)
是的,这是可能的。使用Mapping the Table-Per-Concrete Class (TPC) Inheritance 它可以这样做
public class InheritanceMappingContext : DbContext
{
public DbSet<Action> Action { get; set; }
public DbSet<ActionLog> ActionLog { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ActionLog>().Map(m =>
{
m.MapInheritedProperties(); // add inherited property to actionLog
m.ToTable("ActionLog");
});
modelBuilder.Entity<Action>().Map(m =>
{
m.ToTable("Action");
});
}
}
答案 1 :(得分:0)
当然,映射你的基类:
public class YourBaseClassMapping<T> : EntityTypeConfiguration<T> where T : YourBaseClassEntity
{
protected YourBaseClassMapping()
{
HasKey(x => x.Id);
...
}
}
然后映射继承的类:
public class InheritedClassMapping<T> : EntityTypeConfiguration<T> where T : InheritedClassMapping
{
public InheritedClassMapping()
{
// new mapping for inherited class
}
}
并将两个映射添加到DbModelBuilder作为其他映射:
public class YourDbContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new YourBaseClassMapping());
modelBuilder.Configurations.Add(new InheritedClassMapping());
}
}