![](/img/trans.png)
[英]M-N relation without joint entity not present in .NET Core 3 EF and no docs on why
[英]Remove entity from joint table without affecting parent - EF Core 2.2
我對多對多關系有疑問,我不明白為什么會這樣:
所以我有以下內容:
public class A
{
public Guid Guid { get; set; }
public ICollection<AB> ABs { get; set; }
}
public class B
{
public Guid Guid { get; set; }
public ICollection<AB> ABs { get; set; }
}
public class AB
{
public Guid Guid { get; set; }
public A A { get; set; }
public Guid A_Id { get; set; }
public B B { get; set; }
public Guid B_Id { get; set; }
internal static void OnModelCreating(ModelBuilder builder)
{
builder.Entity<AB>(entity =>
{
entity.HasIndex(e => new { e.A_Id, e.B_Id}).IsUnique();
entity.HasOne(e => e.A)
.WithMany(p => p.ABs)
.HasForeignKey(e => e.A_Id)
.OnDelete(DeleteBehavior.Restrict);
entity.HasOne(e => e.B)
.WithMany(w => w.ABs)
.HasForeignKey(e => e.B_Id)
.OnDelete(DeleteBehavior.Restrict);
});
}
}
我不斷得到:
實體類型“A”和“AB”之間的關聯已被切斷,但該關系被標記為“必需”或隱式必需,因為外鍵不可為空。 如果在斷開所需關系時應刪除依賴/子實體,則設置關系以使用級聯刪除。 考慮使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”來查看鍵值。
問題是我想通過從 A.ABs 中刪除 AB 來打破這種關系,而 EF Core 試圖刪除 A。我不明白發生了什么。 有任何想法嗎?
最好的祝福
你為什么要在 AB class 里面創建模型? 它應該在 dbcontext 中。
並嘗試為您添加密鑰 AB class。 由於您使用的是 v.2.2,它將使 EF 更加可靠。
public class A
{
public Guid Id{ get; set; }
public ICollection<AB> ABs { get; set; }
}
public class B
{
public Guid Id { get; set; }
public ICollection<AB> ABs { get; set; }
}
public class AB
{
public Guid Id { get; set; }
public A A { get; set; }
public Guid A_Id { get; set; }
public B B { get; set; }
public Guid B_Id { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.