我正在尝试指定一个列名称以将“外键”映射到使用 Fluent API。我正在连接到 SQL Express 的一个实例。我搜索过 Stack Overflow 和 Google,但许多不同的配置示例都给了我相同的结果。
产品类别
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; }
}
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);
}
}
问题
当我运行程序并且 EF 创建数据库时的结果是 ParentID
专栏出来NULL
并创建一个名为 ParentProduct_ProductId
的列.此列包含 ParentId 的正确值。
我是第一次将 Fluent API 与 EF 结合使用,所以我将这归咎于缺乏经验。如何让自动生成的列填充 ParentId
专栏代替?
最佳答案
试试这个解决方案:
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);
}
}
关于c# - Entity Framework : How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19548130/