Entity Framework: 如何在自引用的父子关系中指定外键列的名称?

4
我正在尝试使用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; }
}

产品地图到实体框架
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值。

对于使用EF的Fluent API,我还很陌生,所以我把这个问题归结为经验不足。如何使自动生成的列填充ParentId列?

1个回答

1
尝试这个解决方案:

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

嗨,达米安。谢谢你的回复!我使用了HasOptional(x => x.ParentProduct),但我认为这就是你的意思。它仍然给我带来了同样的问题。它创建了ParentProduct_ProductId列而不是使用ParentId列,而ParentId仍然为空。我应该尝试其他配置吗?我注意到很多示例都使用了protected override void OnModelCreating(DbModelBuilder modelBuilder)方法,但我认为这与我创建映射类时使用的相同配置是一样的。这个方法应该在这里完成吗? - imightbealex
我已经弄清楚了,但我还不能发布答案。这与OnModelCreating方法有关。我没有注册映射! - imightbealex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接