Tạo Cascade Delete trong Entity Framework Core

 4/21/2020 |  Admin   3319 lượt xem

(netcore.vn) - Tạo Cascade Delete trong Entity Framework Core

Trong Code-First:

Bàn tìm từ khóa OnDelete trong ApplicationContextModelSnapshot mục Migration.

.OnDelete(DeleteBehavior.Cascade)

Nếu Table chứa mã trên thì đã bao gồm Cascade Delete khi xóa model cha, mặc định sẽ xóa luôn các thư mục con có liên quan.

Có 2 cách khai báo Casecade Delete

  • Sử dụng API:
using (var context = new MyContext())
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Invoice>()
            .HasOne(i => i.Customer)
            .WithMany(c => c.Invoices)
            .IsRequired()
            .OnDelete(DeleteBehavior.Cascade);
    }
}
  • Khai báo trong Model phải có keyword [ForeignKey("ParentID")] cho quan hệ 1 nhiều.

Chúc các bạn thành công.

https://entityframeworkcore.com/saving-data-cascade-delete

liên quan

Làm việc với Stored Procedures trong EF Core và ASP.NET Core  3590

 8/2/2020

Làm việc với Stored Procedures trong EF Core và ASP.NET Core

Xem chi tiết 

Ra mắt Entity Framework Core 5 preview 2  2885

 4/4/2020

Ra mắt Entity Framework Core 5 preview 2

Xem chi tiết 

Lỗi The Include operation for navigation is unnecessary and was ignored because the navigation is not reachable in the final query results trong FE Core  2566

 11/1/2019

Lỗi The Include operation for navigation is unnecessary and was ignored because the navigation is not reachable in the final query results trong FE Core

Xem chi tiết 

Lỗi The LINQ expression could not be translated and will be evaluated locally trong EF Core  2481

 11/1/2019

Lỗi The LINQ expression could not be translated and will be evaluated locally trong EF Core

Xem chi tiết 

Các Lệnh Cơ Bản Về Migration Trong .NET Core  5960

 9/7/2019

Những lệnh cơ bản về Migration trong .NET Core

Xem chi tiết 

Entity Framework Core  4519

 9/3/2019

Entity Framework Core

Xem chi tiết 
Like Fanpage Để Ủng Hộ Chúng Tôi Duy Trì Website