EF 代码优先导航 属性 到相同 table
EF Code First Navigation Property to same table
我是 EF 的新手,正在努力实现以下场景。我有一个实体,我希望导航 属性 到同一实体的另一个实体。例如
public class Stage {
public int ID { get; set; }
public int? NextStageID { get; set; }
public string Name { get; set; }
public virtual Stage NextStage { get; set;}
}
到目前为止我发现的唯一示例是实体具有父/子关系,即导航 属性 是同一实体的 ICollection。我尝试对此进行调整,但无法让它在我的实例中工作。另外,我只需要它是一种方式,即实体没有 'PreviousStage' 属性,只有 'NextStage' 一个。我正在使用 Fluent API 配置。有人可以建议这是否/如何实现吗?
我收到这个错误:
Unable to determine the principal end of an association between the types 'namespace.Stage' and 'namespace.Stage'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations
编辑
刚刚在我稍微简化的示例中意识到,我没有表明 NextStageID 是可选的(int?)。
您可以明确定义关系如下:
public class Stage {
public int ID { get; set; }
public int NextStageID { get; set; }
public string Name { get; set; }
[ForeignKey("NextStageID ")]
public virtual Stage NextStage { get; set;}
}
你需要添加一个parentId和Parent导航属性
和子导航 属性 所以 entity framework 理解这是一个递归关系
检查此 stack Overflow link
中的答案
我是 EF 的新手,正在努力实现以下场景。我有一个实体,我希望导航 属性 到同一实体的另一个实体。例如
public class Stage {
public int ID { get; set; }
public int? NextStageID { get; set; }
public string Name { get; set; }
public virtual Stage NextStage { get; set;}
}
到目前为止我发现的唯一示例是实体具有父/子关系,即导航 属性 是同一实体的 ICollection。我尝试对此进行调整,但无法让它在我的实例中工作。另外,我只需要它是一种方式,即实体没有 'PreviousStage' 属性,只有 'NextStage' 一个。我正在使用 Fluent API 配置。有人可以建议这是否/如何实现吗?
我收到这个错误:
Unable to determine the principal end of an association between the types 'namespace.Stage' and 'namespace.Stage'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations
编辑 刚刚在我稍微简化的示例中意识到,我没有表明 NextStageID 是可选的(int?)。
您可以明确定义关系如下:
public class Stage {
public int ID { get; set; }
public int NextStageID { get; set; }
public string Name { get; set; }
[ForeignKey("NextStageID ")]
public virtual Stage NextStage { get; set;}
}
你需要添加一个parentId和Parent导航属性 和子导航 属性 所以 entity framework 理解这是一个递归关系 检查此 stack Overflow link
中的答案