[英]How do I configure a navigation property to the same table in Entity Framework?
How do I configure Entity Framework using fluent configuration to behave the same way that I would do this with attributes: 如何使用流利的配置来配置Entity Framework,使其行为与我对属性所做的操作相同:
public class Product
{
public int? ParentId { get; set; }
[ForeignKey("ParentId")]
public virtual Product Parent { get; set; }
}
Supposing that you want to create a self referencing entity, I assume that you have a Product
class like this: 假设您要创建一个自引用实体,我假设您有一个如下的
Product
类:
public class Product
{
public int Id { get; set; }
public int? ParentId { get; set; }
public virtual Product Parent { get; set; }
}
In the context, you need to implement the OnModelCreating
method in order to configure the self reference. 在上下文中,您需要实现
OnModelCreating
方法以配置自引用。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().
HasOptional(e => e.Parent).
WithMany().
HasForeignKey(m => m.ParentId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.