简体   繁体   English

Fluent API中的父子关系

[英]Parent-Child Relationship in Fluent API

Okay, this is getting ridiculous as this is turning out to be much more difficult than it has any right to be. 好的,这变得荒谬,因为事实证明,这比任何权利都困难得多。

If I use my original code with no FluentAPI mapping, I have a ParentID field which is not used, and a new field called Node_ID is used. 如果我使用没有FluentAPI映射的原始代码,则会有一个不使用的ParentID字段,并且会使用一个名为Node_ID的新字段。

public class Node {
  public long ID { get; private set; }
  public long ParentID { get; set; }
  public ICollection<Node> Children { get; set; }
}

Here are my various attempts: 这是我的各种尝试:

protected override void OnModelCreating(DbModelBuilder mb)
{
  mb.Entity<Node>()
    .HasMany<Node>(h => h.Children)
    .WithOptional()
    .HasForeignKey(h => h.ParentID);
}

DbUpdateException: Unable to determine a valid ordering for dependent operations. DbUpdateException:无法确定相关操作的有效顺序。 Dependencies may exist due to foreign key constraints, model requirements, or store-generated values. 由于外键约束,模型要求或商店生成的值,可能存在依赖关系。

protected override void OnModelCreating(DbModelBuilder mb)
{
  mb.Entity<Node>()
    .HasMany<Node>(h => h.Children)
    .WithOptional()
    .Map(m => m.MapKey("ParentID"));
}

MetadataException: Schema specified is not valid. MetadataException:指定的架构无效。 Errors: (82,6) : error 0019: Each property name in a type must be unique. 错误:(82,6):错误0019:类型中的每个属性名称都必须是唯一的。 Property name 'ParentID' was already defined. 属性名称“ ParentID”已定义。

[ForeignKey("ParentID")]
public ICollection<Node> Children { get; set; }

protected override void OnModelCreating(DbModelBuilder mb)
{
  mb.Entity<Node>()
    .HasMany<Node>(h => h.Children)
    .WithOptional()
}

DbUpdateException: Unable to determine a valid ordering for dependent operations. DbUpdateException:无法确定相关操作的有效顺序。 Dependencies may exist due to foreign key constraints, model requirements, or store-generated values. 由于外键约束,模型要求或商店生成的值,可能存在依赖关系。

Update 更新

Using the Fluent API code from my first attempt code above (.HasForeignKey), and by making ParentID nullable (public long? ParentID), I have gotten the database to successfully map. 使用上面我的第一个尝试代码(.HasForeignKey)中的Fluent API代码,并通过使ParentID为可空值(公共long?ParentID),我已经获得了数据库以成功进行映射。 Is there any way to do this without making the FK nullable? 有什么方法可以使FK为空? I would like the key to be 0 when no parent exists. 我希望没有父级时该键为0。 If not, oh well, I will deal. 如果没有,我会处理的。

没有办法避免可为空的ParentId您告诉EF父对象是可选的(否则必须不可以使用该表),并且因为相关的FK属性必须可为空。

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

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