0

我想在ASP.NET Core中創建用戶關係表並遇到一些問題。如果因爲這個原因必須禁用級聯刪除,我該如何防止孤兒?創建用戶關係表

錯誤:

Introducing FOREIGN KEY constraint 'FK_UserRelationships_AspNetUsers_User2Id' on table 'UserRelationships' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. 

ApplicationDbContext.cs:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser> 
{ 
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
     : base(options) 
    { 
    } 

    protected override void OnModelCreating(ModelBuilder builder) 
    { 
     base.OnModelCreating(builder); 
     builder.Entity<UserRelationship>().HasKey(x => new { x.User1Id, x.User2Id }); 
    } 

    public DbSet<UserRelationship> UserRelationships { get; set; } 
} 

我目前的模型:

public class UserRelationship 
{ 
    public byte RelationshipType { get; set; } 
    public ApplicationUser User1 { get; set; } 
    public string User1Id { get; set; } 
    public ApplicationUser User2 { get; set; } 
    public string User2Id { get; set; } 
} 

回答

0

你有你的ApplicationUsers根據需要使EF將級聯默認情況下刪除兩次到同一班(見here)。

你需要告訴它不要:

builder.Entity<UserRelationship>().HasOne(ur => ur.User1).WithMany().HasForeignKey(ur => ur.UserId1).WillCascadeOnDelete(false); 

builder.Entity<UserRelationship>().HasOne(ur => ur.User2).WithMany().HasForeignKey(ur => ur.UserId2).WillCascadeOnDelete(false); 
+0

沒有命名HasRequired()的方法。我想念什麼? – Zack

+0

如果我禁用級聯刪除,我該如何防止孤兒? – Zack

+0

對不起,沒有意識到它是EF Core。請參閱[這裏](https://docs.microsoft.com/en-us/ef/core/modeling/relationships)。當你刪除UserRelationship時,我假設你不想刪除用戶。如果你刪除了一個用戶,你可以檢查現有的關係記錄並刪除它們(請參閱[這裏](https://stackoverflow.com/questions/16565078/delete-parent-with-children-in-one-to-many -關係))。 –