這個問題很容易復制,但我不知道解決它的正確方法。
課程:
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; }
}
我正在ApplicationUser為用戶表使用內置身份類。生成遷移時我沒有遇到任何錯誤,但是每當我嘗試更新資料庫時,我都會收到一個錯誤:
在表 'Employee' 上引入 FOREIGN KEY 約束可能會導致回圈或多個級聯路徑。指定 ON DELETE NO ACTION 或 ON UPDATE NO ACTION,或修改其他 FOREIGN KEY 約束。
使用 Fluent API 解決此問題的適當方法是什么?
專案型別:ASP.NET Core MVC
uj5u.com熱心網友回復:
這個問題的解決方法是:
只需將一個 FK 配置為非級聯,僅此而已。不應更改遷移檔案,不應通過使鍵可為空來更改自然關系。- @gert-阿諾德
uj5u.com熱心網友回復:
第一道工序:-
首先,將您的遷移檔案(cascadeDelete: true)放入,(cascadeDelete: false)如果仍然不起作用,則繼續。
使您的外鍵屬性可以為空,這應該可以作業。
更新您的代碼,如下所示:-
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; }
}
如果不起作用,請嘗試第二個程序:-
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; }
}
將此添加到您的 DbContext 類:-
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);
}
第三道工序:-
另一種選擇是通過添加此 (EF6) 來洗掉所有 CASCADE DELETES :-
modelbuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelbuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
希望它能解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381539.html
