I am trying to a create a many-to-many relationship by using a linking table Booking and this got me stuck juggling between two errors and I'm very confused.
Introducing FOREIGN KEY constraint 'FK_Bookings_WorkProfiles_WorkProfileId' on table 'Bookings' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
Which I tried to solve going into Context class modelBuilder.
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Booking>()
.HasOne(e => e.UserProfile)
.WithMany()
.OnDelete(DeleteBehavior.Restrict);
}
But this creates the following error:
The foreign key property 'Booking.UserProfileId1' was created in shadow state because a conflicting property with the simple name 'UserProfileId' exists in the entity type, but is either not mapped, is already used for another relationship, or is incompatible with the associated primary key type. See https://aka.ms/efcore-relationships for information on mapping relationships in EF Core.
I am very confused. I tried fixing this error by removing the foreign key etc. and I get back to first error again.
What I would like: deleting UserProfile or WorkProfile to not cascade to delete booking so I don't get the the first error.
public class Booking : BaseDateClass
{
public int BookingId { get; set; }
[ForeignKey("AdvertTreatmentId")]
public AdvertTreatment AdvertTreatment { get; set; }
[ForeignKey("UserProfileId")]
public UserProfile UserProfile { get; set; }
[ForeignKey("WorkProfileId")]
public WorkProfile WorkProfile { get; set; }
}
public class UserProfile : BaseDateClass
{
public int UserProfileId { get; set; }
public List<Booking> Bookings { get; set; }
}
public class WorkProfile : BaseDateClass
{
public int WorkProfileId { get; set; }
[ForeignKey("WorkAccountId")]
public WorkAccount WorkAccount { get; set; }
public List<Advert>? Adverts { get; set; }
public List<WorkProfileLanguage> WorkProfileLanguages { get; set; }
public List<Booking> Bookings { get; set; }
}
Edit: this is an Entity Framework Core 6.0.5 project
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite" Version="6.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>