我似乎无法想出这个。我根据这里找到的信息尝试了一个解决方案:ASP.Net Forum,但这个问题不同,不适合我。
这也不起作用:Entity Framework many-to-many self-reference(Efcore中不存在HasMany + WithMany)
也不是:Entity Framework Core: many-to-many self referencing relationship
这是我的情景:
public class ApplicationUser
{
public int Id { get; set; }
public ICollection<CustomerContractorBan> Bans { get; set; }
}
public enum BanType
{
Contractor,
Customer
}
public class CustomerContractorBan
{
public BanType BannedBy { get; set; }
[ForeignKey(nameof(CustomerId))]
public ApplicationUser Customer { get; set; }
public int CustomerId { get; set; }
[ForeignKey(nameof(ContractorId))]
public ApplicationUser Contractor { get; set; }
public int ContractorId { get; set; }
public DateTimeOffset Time { get; set; }
}
/// <inheritdoc />
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CustomerContractorBan>().HasKey(d => new { d.ContractorId, d.CustomerId, d.BannedBy });
modelBuilder.Entity<CustomerContractorBan>()
.HasOne(d => d.Contractor)
.WithMany(d => d.Bans)
.HasForeignKey(d => new { d.ContractorId })
.OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<CustomerContractorBan>()
.HasOne(d => d.Customer)
.WithMany(d => d.Bans)
.HasForeignKey(d => new { d.CustomerId })
.OnDelete(DeleteBehavior.Restrict);
}
我想要实现的目标:
我目前得到的例外是:
无法在'ApplicationUser.Bans'和。之间创建关系 'CustomerContractorBan.Customer',因为已经有了 'ApplicationUser.Bans'和。之间的关系 'CustomerContractorBan.Contractor'。导航属性只能 参与单一的关系
我这样做错了还是efcore 2.1的限制?我见过类似的代码解决了类似的问题。但是在我的情况下,我似乎无法在没有异常的情况下两次调用模型构建器。
PS:这曾经有效,直到我将BannedBy添加到属性+键。显然,任何参与者都应该能够相互禁止。