Reputation: 43
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.
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; }
}
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 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?
Upvotes: 4
Views: 884
Reputation: 156
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);
}
}
Upvotes: 1