简体   繁体   English

如何在Entity Framework中为同一表配置导航属性?

[英]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.

相关问题 如何在没有反向导航属性的实体框架中配置外键? - How to configure foreign key in Entity Framework without an inverse navigation property? 如何在实体框架中找到属性映射到的表和列? - How do I find the table and column a property maps to in the Entity Framework? 在实体框架中,如何配置影子拥有的实体? - In Entity Framework how do I configure a shadow owned entity? 实体框架导航属性 - Entity Framework navigation property 如何在类库项目中配置实体框架? - How do I configure Entity framework in class Library project? 实体类型上已存在同名的属性或导航 - 如何在实体框架的迁移场景中添加外键 - Property or navigation with the same name already exists on entity type - how to add foreign keys in migration scenario of Entity Framework 如何在实体框架中添加导航属性 - How to add navigation property in the Entity Framework 如何在实体框架中保存/更新导航属性? - How to Save/Update navigation property in Entity Framework? 如何使用集合导航属性更新实体(使用MVC2) - how do I update an entity with a collection navigation property (with MVC2) 实体框架可以将同一列映射到导航属性和外键吗 - Can Entity Framework map the same column to a Navigation Property and a Foreign Key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM