简体   繁体   中英

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. I am connecting to an instance of SQL Express. I have searched Stack Overflow and Google, but many of the different configuration examples gave me the same result.


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 . This column contains the correct values for the ParentId.

I'm new to using the Fluent API with EF, so I'm chalking this one up to inexperience. How do I get the auto-generated column to fill the ParentId column instead?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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