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

StackOverflow https://stackoverflow.com/questions/19548130

Question

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?

Était-ce utile?

La solution

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);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top