C# 映射期间将外键作为属性公开时发生冲突

C# 映射期间将外键作为属性公开时发生冲突,c#,ef-code-first,entity-framework-5,fluent-interface,C#,Ef Code First,Entity Framework 5,Fluent Interface,我有以下表格结构: Affiliations Id Party1 Party2 1 100 200 2 300 400 以及通过附属机构的FKs引用的表 使用我的参与方实体(未显示),我使用Fluent API定义表之间的关系: modelBuilder.Entity<Party>() .HasMany(c => c.LeftPartyAffiliations) .WithR

我有以下表格结构:

Affiliations

Id    Party1    Party2
1     100       200
2     300       400
以及通过附属机构的FKs引用的表

使用我的参与方实体(未显示),我使用Fluent API定义表之间的关系:

modelBuilder.Entity<Party>()
            .HasMany(c => c.LeftPartyAffiliations)
            .WithRequired()
            .Map(m => m.MapKey("Party1"));

modelBuilder.Entity<Party>()
            .HasMany(c => c.RightPartyAffiliations)
            .WithRequired()
            .Map(m => m.MapKey("Party2"));
…但这是不可能的,因为我已经在通过Fluent API从Party映射到我的左右集合来定义我的关系

一个完美的场景将允许我进行Fluent API映射,这将创建列和关系,并允许我通过附属映射中定义的物理列访问Party1和Party2 Id

如果我尝试在实体和Fluent API中物理定义属性,我会得到:

类型中的每个属性名称都必须是唯一的。属性名已被删除 定义为“xxx”


是否有解决此问题的方法,或者有一种方法可以将一列映射到多个属性,而无需向数据库中实际添加其他字段?

您可以使用
HasForeignKey
而不是
MapKey

modelBuilder.Entity<Party>()
    .HasMany(c => c.LeftPartyAffiliations)
    .WithRequired()
    .HasForeignKey(pa => pa.Party1)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Party>()
    .HasMany(c => c.RightPartyAffiliations)
    .WithRequired()
    .HasForeignKey(pa => pa.Party2)
    .WillCascadeOnDelete(false);
modelBuilder.Entity()
.HasMany(c=>c.LeftPartyAffiliations)
.WithRequired()
.HasForeignKey(pa=>pa.Party1)
.WillCascadeOnDelete(假);
modelBuilder.Entity()
.HasMany(c=>c.RightPartyAffiliations)
.WithRequired()
.HasForeignKey(pa=>pa.Party2)
.WillCascadeOnDelete(假);

它将模型类中的属性映射到数据库中的外键列。禁用级联删除在这里是必要的(至少对于两个关系中的一个),否则您将有一个从
Party
PartyAffiliation
的多级联删除路径,这在SQL Server中是禁止的。

将从属关系表的结构更改为泛型会更容易吗?包含以下字段:Id、PartyId、Type。这样,您可以按第三列进行筛选,您可以随意添加广告(party1,party2,party3,…,n),而不是固定两列columns@amhed我应该注意到,我不控制数据库结构。我基本上是首先使用代码来创建基于我无法控制的设计的结构。数据库是否已经有了密钥?为什么不使用数据库优先的方法呢?
public class PartyAffiliation
{
    ...

    [Column("Party1")]
    public int Party1 { get; set; }

    [Column("Party2")]
    public int Party2 { get; set; }

    ...
}
modelBuilder.Entity<Party>()
    .HasMany(c => c.LeftPartyAffiliations)
    .WithRequired()
    .HasForeignKey(pa => pa.Party1)
    .WillCascadeOnDelete(false);

modelBuilder.Entity<Party>()
    .HasMany(c => c.RightPartyAffiliations)
    .WithRequired()
    .HasForeignKey(pa => pa.Party2)
    .WillCascadeOnDelete(false);