I can't seem to figure this one out. I tried a solution along the lines of information found here: ASP.Net Forum, but that issue is different enough to not work for me.
This does not work either: Entity Framework many-to-many self-reference (HasMany+WithMany does not exist in Efcore)
nor this: Entity Framework Core: many-to-many self referencing relationship
This is my scenario:
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);
}
What i am trying to achieve:
- User 1 should be able to ban user 2 With BannedBy=Contractor
- User 2 should be able to ban user 1 With BannedBy=Customer
The exception i am currently getting is:
Cannot create a relationship between 'ApplicationUser.Bans' and 'CustomerContractorBan.Customer', because there already is a relationship between 'ApplicationUser.Bans' and 'CustomerContractorBan.Contractor'. Navigation properties can only participate in a single relationship
Am i doing this wrong or is this a limitation of efcore 2.1? I've seen similar code resolve similar issues. However in my case i can't seem to call the modelbuilder twice without getting an exception.
PS: This used to work until i added BannedBy to the properties+keys. Obviously either participant should be able to ban each other.