[英]Remove entity from joint table without affecting parent - EF Core 2.2
I have an issue with many-to-many relationship, and I do not understand why it is behaving this way:我对多对多关系有疑问,我不明白为什么会这样:
so I have the following:所以我有以下内容:
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);
});
}
}
I am keep getting:我不断得到:
The association between entity types 'A' and 'AB' has been severed but the relationship is either marked as 'Required' or is implicitly required because the foreign key is not nullable.实体类型“A”和“AB”之间的关联已被切断,但该关系被标记为“必需”或隐式必需,因为外键不可为空。 If the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.如果在断开所需关系时应删除依赖/子实体,则设置关系以使用级联删除。 Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看键值。
Issue is that I want to break the relationship, by deleting AB from A.ABs, and EF Core tries to delete A. I do not understand what's going on.问题是我想通过从 A.ABs 中删除 AB 来打破这种关系,而 EF Core 试图删除 A。我不明白发生了什么。 Any ideas?有任何想法吗?
Best regards最好的祝福
Why did you put on modelcreating inside of AB class?你为什么要在 AB class 里面创建模型? It should be inside of dbcontext.它应该在 dbcontext 中。
And try add a key to you AB class too.并尝试为您添加密钥 AB class。 Since you are using v.2.2 it will make EF more relaible.由于您使用的是 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.