【问题标题】:Entity Framework: How to specify the name of Foreign Key column on a self-referencing Parent-Child relationship?实体框架:如何在自引用父子关系上指定外键列的名称?
【发布时间】:2023-03-05 11:46:01
【问题描述】:

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

我不熟悉将 Fluent API 与 EF 一起使用,因此我将这归咎于缺乏经验。如何让自动生成的列填充 ParentId 列?

【问题讨论】:

    标签: c# entity-framework self-reference


    【解决方案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 =&gt; x.ParentProduct),但我认为这就是你的意思。它仍然给我同样的问题。它创建ParentProduct_ProductId 列而不是使用ParentId 列,并且ParentId 仍然为NULL。我应该尝试其他配置吗?我注意到很多示例都使用protected override void OnModelCreating(DbModelBuilder modelBuilder) 方法,但我认为这与我通过创建映射类使用的配置相同。应该改用这种方法吗?
    • 我想通了,但我还不能发布答案。它与OnModelCreating 方法有关。我没有注册映射!
    猜你喜欢
    • 2012-04-14
    • 1970-01-01
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    相关资源
    最近更新 更多