[英]EF Core handle shadow foreign key DeleteBehaviour
我希望能夠在刪除影子外鍵屬性的相關實體時更改行為。
public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Book> Books { get; set; }
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
}
此設置將在書實體中創建一個影子屬性“AuthorId”,並且可以根據需要為空。 現在我希望當我刪除作者時,所有相關書籍都會將“AuthorId”外鍵設置為null
。 我怎樣才能做到這一點?
只需在 DbContext 中配置刪除行為:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasOne<Author>()
.WithMany(a => a.Books)
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.SetNull);
base.OnModelCreating(modelBuilder);
}
例如:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Linq;
namespace EfCore3Test
{
public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Book> Books { get; } = new HashSet<Book>();
}
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
}
public class Db : DbContext
{
public DbSet<Author> Authors { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>()
.HasOne<Author>()
.WithMany(a => a.Books)
.HasForeignKey("AuthorId")
.OnDelete(DeleteBehavior.SetNull);
base.OnModelCreating(modelBuilder);
}
public static readonly ILoggerFactory MyLoggerFactory
= LoggerFactory.Create(builder => { builder.AddConsole(); });
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=localhost;Database=EFCore3Test;Integrated Security = true", a => a.UseRelationalNulls(true))
.ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Information)))
.UseLoggerFactory(MyLoggerFactory);
base.OnConfiguring(optionsBuilder);
}
}
class Program
{
static void Main(string[] args)
{
using (var db = new Db())
{
db.Database.EnsureDeleted();
db.Database.EnsureCreated();
var a = new Author();
for (int i = 0; i < 10; i++)
{
var b = new Book();
a.Books.Add(b);
}
db.Authors.Add(a);
db.SaveChanges();
}
using (var db = new Db())
{
var a = db.Authors.First();
db.Authors.Remove(a);
db.SaveChanges();
}
}
}
}
對於 SQL Server,這是生成的 Book 表:
CREATE TABLE [Book] (
[BookId] int NOT NULL IDENTITY,
[Title] nvarchar(max) NULL,
[AuthorId] int NULL,
CONSTRAINT [PK_Book] PRIMARY KEY ([BookId]),
CONSTRAINT [FK_Book_Authors_AuthorId] FOREIGN KEY ([AuthorId]) REFERENCES [Authors] ([AuthorId]) ON DELETE SET NULL
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.