EF Core 外键可为空设置指南 - 使用 HasOne 和 HasMany
在 EF Core 中,可以使用'HasOne'或'HasMany'方法来设置外键可为空。
假设有两个实体类'Parent'和'Child',其中'Child'类有一个可为空的外键'ParentId',可以按照以下方式设置外键可为空:
public class Parent
{
public int Id { get; set; }
public ICollection<Child> Children { get; set; }
}
public class Child
{
public int Id { get; set; }
public int? ParentId { get; set; }
public Parent Parent { get; set; }
}
public class AppDbContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Child>()
.HasOne(c => c.Parent)
.WithMany(p => p.Children)
.HasForeignKey(c => c.ParentId)
.IsRequired(false); // 设置外键可为空
}
}
在上述代码中,通过在'HasForeignKey'方法中使用'IsRequired(false)'来设置外键可为空。
原文地址: https://www.cveoy.top/t/topic/qjzu 著作权归作者所有。请勿转载和采集!