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

标签 c# entity-framework self-reference

我正在尝试指定一个列名称以将“外键”映射到使用 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/

相关文章:

c# - 为 Entity Framework Core 中的所有数据库创建并应用迁移

swift - 了解 Swift 闭包捕获

c# - SyncRoot 模式有什么用?

entity-framework - MVVM + Entity Framework 架构困惑

c# - 添加 Azure Function (v3) 绑定(bind)到 BlobTrigger 的 RequestTelemetry 的自定义属性

wpf - 为什么在我的WPF应用程序中有时会发生此 Entity Framework 崩溃?

c# - 在该类的构造函数中实例化类变量

Python:从自身内部获取对函数的引用

c# - .Net 4.5.1中GCLatencyMode和gcConcurrent如何交互(使用gcserver)

c# - 在 C# 中注册 Win + L 热键时出现问题