Entity framework 实体框架-多个实体的虚拟表(代码优先)

Entity framework 实体框架-多个实体的虚拟表(代码优先),entity-framework,inheritance,code-first,Entity Framework,Inheritance,Code First,我们正在构建一个包含多个实体的上下文。所有实体都构建在ID为(guid)的抽象类上 我们希望所有实体都与一个公共日志表有关系,但是由于命名原因,我们无法让EFCF理解这种关系 public class Log { public BaseEntity Entity {get;set;} public Guid EntityID {get;set;} } public class Example : BaseEntity { public virtual ICollection<

我们正在构建一个包含多个实体的上下文。所有实体都构建在ID为(guid)的抽象类上

我们希望所有实体都与一个公共日志表有关系,但是由于命名原因,我们无法让EFCF理解这种关系

public class Log {
  public BaseEntity Entity {get;set;}
  public Guid EntityID {get;set;}
}

public class Example : BaseEntity {
  public virtual ICollection<Log> Logs {get;set;}
}

日志类上的一组属性,一切正常。添加新的日志条目时会出现问题。

我希望找到一个可行且有效的解决方案,将公共字段抽象为基类

在模型构建中使用MapInheritedProperties()(并遵循)

modelBuilder.Entity().Map(x=>x.MapInheritedProperties());
modelBuilder.Entity()
.HasRequired(x=>x.BaseEntity)
.WithMany(x=>x.Logs)
.Map(x=>
{
x、 ToTable(“示例”);
x、 MapKey(新的[]{“ID”});
})
.WillCascadeOnDelete(假);

现在,我可以将“虚拟”表分配给任何实体,只要它们派生自基类。

创建日志时您会做什么?您是否尝试将其转换为基本实体?也许是一个类型值,这样您可以手动重铸回您的类型?或者您可以使它只是一个基于GUID的getter?逻辑地思考。您能在关系数据库中创建这样的FK吗?
[ForeignKey("EntityID")]
public Example Example {get;set;}
[ForeignKey("EntityID")]
public Example5 Example5 {get;set;}
[ForeignKey("EntityID")]
public Example2 Example2 {get;set;}
modelBuilder.Entity<Models.Example>().Map(x => x.MapInheritedProperties());

modelBuilder.Entity<Models.Log>()
    .HasRequired(x => x.BaseEntity)
    .WithMany(x => x.Logs)
    .Map(x =>
    {
        x.ToTable("Example");
        x.MapKey(new[] { "ID" });
    })
    .WillCascadeOnDelete(false);