And*_*man 4 c# entity-framework entity-framework-core
我有两节课:
public class DbLibrary
{
public Guid Id { get; set; }
public string Name { get; set; }
public List<DbDepartment> Departments { get; set; } = new List<DbDepartment>();
}
public class DbDepartment
{
public Guid Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在这个模型中我需要DbDepartment没有包含链接的属性DbLibrary.但是我需要在数据库端进行级联删除.为此我将shadow属性添加到DbDepartment.这是外键.如何将主键DbLibrary类与shadow属性相关联?
这是我的尝试:
protected override void OnModelCreating(ModelBuilder builder)
{
// Create the shadow property
var id = builder.Entity<DbDepartment>().Property<Guid>("LibraryId");
// Create the relationship for cascade delete
builder.Entity<DbLibrary>().HasMany(n => n.Departments)
.WithOne(m => id /* it is wrong */).OnDelete(DeleteBehavior.Cascade);
}
Run Code Online (Sandbox Code Playgroud)
阴影属性表示基本属性(在您的情况下为FK),不能用于创建导航属性.
为了在没有导航属性的情况下配置关系结束,可以使用相应的Has/无With参数重载.FK是影子还是常规属性并不重要.在配置关联的FK using HasForeignKey方法时很重要,这意味着对于shadow属性,您必须使用带string属性名称的重载而不是lambda表达式.
这是所需的流畅配置:
builder.Entity<DbLibrary>()
.HasMany(e => e.Departments)
.WithOne()
.HasForeignKey("LibraryId")
.OnDelete(DeleteBehavior.Cascade);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2596 次 |
| 最近记录: |