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

c# entity-framework entity-framework-core

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

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 OmegaContext : IdentityDbContext<OmegaUser,OmegaRole,int>
{
    public DbSet<Log> Logs { get; set; }
    public DbSet<Organization> Organizations { get; set; }
    public DbSet<OrganizationLogin> OrganizationLogins { get; set; }
    public DbSet<OrganizationRole> OrganizationRoles { get; set; }

    public OmegaContext()
    {

    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<OrganizationLogin>(orgLogin =>
        {
            orgLogin.HasAlternateKey(o => new {o.User, o.Organization});
        });

    }
}

如果我刪除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:

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<OrganizationUnit>(
            orgUnit =>
            {
                orgUnit.HasOne(ou => ou.Parent)
                    .WithMany(ou => ou.Children)
                    .OnDelete(DeleteBehavior.Restrict)
                    .HasForeignKey(ou => ou.ParentId);
            });
        builder.Entity<OrganizationUnitMember>(member =>
        {
            member.HasAlternateKey(m => new {m.OrganizationUnitId, m.UserId});
        });

    }

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



Related

許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow
許可下: CC-BY-SA with attribution
不隸屬於 Stack Overflow