This issue can be replicated easily, but I do not know the correct way to resolve it.
Classes:
public class Employee : IEntity<Guid>
{
public Guid Id { get; set; }
public Guid ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public Guid CompanyId { get; set; }
public Company Company { get; set; }
}
public class Company : IEntity<Guid>
{
public Guid Id { get; set; }
public string Name { get; set; }
public IList<Employee> Employees { get; set; }
}
I'm using built-in identity ApplicationUser
class for user table.
I'm not getting any kind of error when generating migration but whenever I'm trying to update the database, I get an error:
Introducing FOREIGN KEY constraint on table 'Employee' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
What is the appropriate way to resolve this issue using Fluent API?
Project type: ASP.NET Core MVC
CodePudding user response:
First Process:-
First of all make your migration file (cascadeDelete: true)
into (cascadeDelete: false)
if still not work then go forward.
Make your Foreign key attributes nullable and that should work.
Update your code like below:-
public class Employee : IEntity<Guid>
{
public Guid Id { get; set; }
[ForeignKey("ApplicationUserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public Guid? ApplicationUserId { get; set; }
[ForeignKey("CompanyId")]
public virtual Company Company { get; set; }
public Guid? CompanyId { get; set; }
}
If not work then try second process:-
public class Employee : IEntity<Guid>
{
public Guid Id { get; set; }
public Guid ApplicationUserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public Guid CompanyId { get; set; }
public Company Company { get; set; }
}
Add this to your DbContext class:-
protected override void OnModelCreating(ModelBuilder modelbuilder)
{
base.OnModelCreating(modelbuilder);
modelbuilder.Entity<Employee>()
.HasOne(b => b.ApplicationUser )
.WithMany(ba => ba.Employee)
.HasForeignKey(bi => bi.ApplicationUserId );
//For Company
modelbuilder.Entity<Employee>()
.HasOne(b => b.Company )
.WithMany(ba => ba.Employee)
.HasForeignKey(bi => bi.CompanyId);
}
Third Process:-
Another option is to remove all CASCADE DELETES by adding this (EF6) :-
modelbuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelbuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
Hope it will resolve your issue.
CodePudding user response:
Solution for this problem is:
only have to configure one FK as non-cascading, that's all. Migration files shouldn't be altered and the nature relationships shouldn't be changed by making keys nullable. - @gert-arnold