简体   繁体   English

EF Core 级联删除

[英]EF Core Cascade Delete

Context: Visual Studio, Blazor .NET 5, Azure SQL Server上下文:Visual Studio,Blazor .NET 5,Azure Z9778840A0100CB30C58287674BZ服务器

I have an entity with two FK.我有一个有两个 FK 的实体。 If I delete a record in one the FK tables I get the typical Referencing error.如果我删除 FK 表中的一条记录,我会收到典型的引用错误。 In https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete it seems to say the Cascade Delete is the default.https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete中似乎说 Cascade Delete 是默认设置。 When I generate a new Migration (add-migration cascade) there is no当我生成一个新的迁移(添加迁移级联)时,没有

.OnDelete(DeleteBehavior.Cascade)
.IsRequired();

... attached to the FK properties of the entity in question in the Migration documents generated. ...附加到生成的迁移文档中相关实体的 FK 属性。

  1. Is there an Attribute that can be applied to the FK property in the entity class?是否有可以应用于实体 class 中的 FK 属性的属性?

  2. Is there some other way of doing this in code?在代码中还有其他方法可以做到这一点吗?

  3. How do I modify the migration documentation to entrench th?如何修改迁移文档以巩固 th?

This is what I ended up doing.. I did it in code这就是我最终要做的......我在代码中做到了

 public async Task DeleteRound(int Id) { var round = _context.Rounds.Where(e => e.Id==Id).Include(e => e.Activitys).First(); _context.Rounds.Remove(round); await _context.SaveChangesAsync(); }

I had to add the following to the Round Class:我必须将以下内容添加到 Round Class:

 public IList<Activity> Activitys { get; } = new List<Activity>();

No further code required.无需进一步的代码。 No need to populate the list as above.无需像上面那样填充列表。 It seems that EF is doing it seamlessly.似乎 EF 正在无缝地做到这一点。 No need to annotate the Migration files.无需注释迁移文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM