我正试图在管理角色的组织中管理用户的成员身份。我想限制用户在组织中只有一个成员资格。我是通过创建一个复合键来做到这一点的。但是,当我尝试创建初始迁移时,我收到错误:
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代码,则会成功创建迁移。
编辑:正如评论中所提到的,问题在于我引用了类而不是具有实体键的属性答案 0 :(得分:4)
根据要求,这是我的解决方案:
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