简体   繁体   English

实体框架:如何在自引用父子关系上指定外键列的名称?

[英]Entity Framework: How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship?

I am trying to specify a column name to map a "Foreign Key" to using the Fluent API. 我正在尝试指定列名以将“外键”映射到使用Fluent API。 I am connecting to an instance of SQL Express. 我正在连接到SQL Express的一个实例。 I have searched Stack Overflow and Google, but many of the different configuration examples gave me the same result. 我搜索过Stack Overflow和Google,但许多不同的配置示例给了我相同的结果。


Product Class 产品类别

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int? ParentId { get; set; }
    public virtual Product ParentProduct { get; set; }
    public virtual ICollection<Product> ChildProducts { get; set; }
}


Product Map to Entity Framework 产品映射到实体框架

public class ProductMap : EntityTypeConfiguration<Product>
{
    public ProductMap() {
        HasKey(p => p.ProductId);

        Property(p => p.Name)
            .IsRequired();

        // Self referencing foreign key association 
        Property(c => c.ParentId)
            .IsOptional();

    HasMany(c => c.ChildProducts)
        .WithOptional(c => c.ParentProduct)
        .HasForeignKey(c => c.ParentId);
    }
}


The Issue 问题

The result when I run the program and EF creates the db is that the ParentID column comes out NULL and it creates a column that's called ParentProduct_ProductId . 当我运行程序并且EF创建数据库时,结果是ParentID列出现NULL并且它创建了一个名为ParentProduct_ProductId的列。 This column contains the correct values for the ParentId. 此列包含ParentId的正确值。

I'm new to using the Fluent API with EF, so I'm chalking this one up to inexperience. 我不熟悉使用Fluent API和EF,所以我将这个问题归结为缺乏经验。 How do I get the auto-generated column to fill the ParentId column instead? 如何让自动生成的列填充ParentId列?

Try this solution: 尝试此解决方案:

public class ProductMap : EntityTypeConfiguration<Product>
{
    public ProductMap() {
        HasKey(p => p.ProductId);

        Property(p => p.Name)
            .IsRequired();

        // Self referencing foreign key association 
        Property(c => c.ParentId)
            .IsOptional();

        HasOptional(x => x.Parent)
            .WithMany(x => x.ChildProducts)
            .HasForeignKey(x => x.ParentId)
            .WillCascadeOnDelete(false);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM