複合密鑰實體框架7“無法將屬性添加到實體類型


我正試圖在管理角色的組織中管理用戶的成員身份。我想限制用戶在組織中只有一個成員資格。我是通過創建一個複合鍵來做到這一點的。但是,當我嘗試創建初始遷移時,我收到錯誤:

InvalidOperationException:無法將屬性“User”添加到實體類型“OrganizationLogin”,因為實體類型“OrganizationLogin”上已存在具有相同名稱的導航屬性。

成員實體

public class OrganizationLogin
{
    public int OrganizationLoginId { get; set; }
    public OrganizationRole Role { get; set; }
    public Organization Organization { get; set; }
    public OmegaUser User { get; set; } 

}

我的DBContext,我嘗試定義組合鍵:

public class OrganizationLogin
{
    public int OrganizationLoginId { get; set; }
    public OrganizationRole Role { get; set; }
    public Organization Organization { get; set; }
    public OmegaUser User { get; set; } 

}

如果我刪除OnModelCreating代碼,則會成功創建遷移。

編輯:正如評論中提到的,問題是我引用了類而不是具有實體鍵的屬性

熱門答案

根據要求,這是我的解決方案:

public class OrganizationUnitMember
{
    public int OrganizationUnitMemberId { get; set; }
    public int UserId { get; set; }
    public int OrganizationUnitId { get; set; }
    [ForeignKey("UserId")]
    public virtual OmegaUser User { get; set; }
    [ForeignKey("OrganizationUnitId")]
    public virtual OrganizationUnit OrganizationUnit { get; set; }
    public int RoleId { get; set; }
    [ForeignKey("RoleId")]
    public virtual OrganizationRole Role { get; set; }
}

和DbContext:

public class OrganizationUnitMember
{
    public int OrganizationUnitMemberId { get; set; }
    public int UserId { get; set; }
    public int OrganizationUnitId { get; set; }
    [ForeignKey("UserId")]
    public virtual OmegaUser User { get; set; }
    [ForeignKey("OrganizationUnitId")]
    public virtual OrganizationUnit OrganizationUnit { get; set; }
    public int RoleId { get; set; }
    [ForeignKey("RoleId")]
    public virtual OrganizationRole Role { get; set; }
}

我不得不添加引用實體的ID





許可下: CC-BY-SA
不隸屬於 Stack Overflow
這個KB合法嗎? 是的,了解原因