如何将导航属性配置为Entity Framework中的同一个表? [英] How do I configure a navigation property to the same table in Entity Framework?

查看:186
本文介绍了如何将导航属性配置为Entity Framework中的同一个表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用流畅的配置来配置Entity Framework,使其与属性相同:

How do I configure Entity Framework using fluent configuration to behave the same way that I would do this with attributes:

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:

public class Product
{
    public int Id { get; set; }

    public int? ParentId { get; set; }

    public virtual Product Parent { get; set; }
}

在上下文中,您需要实现 OnModelCreating 方法,以配置自引用。

In the context, you need to implement the OnModelCreating method in order to configure the self reference.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Product>().
       HasOptional(e => e.Parent).
       WithMany().
       HasForeignKey(m => m.ParentId);
}

这篇关于如何将导航属性配置为Entity Framework中的同一个表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆