Entity Framework Code First 中的多个自引用属性

Multiple self referenced properties in Entity Framework Code First

我有一个 class,它本身包含两个导航属性。

public class Entity
{
    public int Id { get; set; }    
    public Entity Parent { get; set; }    
    public Entity BaseEntity { get; set; }
}

当我 运行 应用程序 EF 抛出一个 expcetion 说 "Unable to determine the principal end of an association between the types 'Test.Entity' and 'Test.Entity'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.".

据我所知,当定义一对一关系时会引发此异常,并且没有为 EF 提供正确确定关系双方的提示。

现在我有两个问题。

首先,这里为什么会抛出这个异常? EF 是否以某种方式将这种情况视为一对一关系?

其次,如何使用属性解决这个问题? 我知道以下 Fluent API 代码可以解决问题,但我对属性更满意。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Entity>().HasOptional(e => e.Parent).WithOptionalDependent();
    modelBuilder.Entity<Entity>().HasOptional(e => e.BaseEntity).WithOptionalDependent();
}

我在 MSDN 上找到了问题的答案。

https://social.msdn.microsoft.com/Forums/en-US/08bba96a-20b2-4a3c-9e0e-a5475b703dfe/code-first-self-referencing-foreign-key?forum=adodotnetentityframework

并且根据批准的答案(由 Rowan Miller 提供),以下代码正确描述了这种关系(不是我的代码)。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{         
    modelBuilder.Entity<AssetType>().HasOptional(a => a.parent).WithMany();
    modelBuilder.Entity<AssetType>().HasOptional(a => a.baseAssetType).WithMany();
}