【问题标题】:Mapping EF Foreign key with different names映射具有不同名称的 EF 外键
【发布时间】:2021-06-10 18:59:06
【问题描述】:

我有以下域类:

public class Product
{
  public Guid? Id { get; set; }
  public string? Name { get; set; }
}

public class Order
{
  public Guid? Id { get; set; }
  public string? Address{ get; set; }
  public Guid? ProductId{ get; set; }
}

我没有使用导航属性来设置外键,而是按如下方式进行:

    public void Configure(EntityTypeBuilder<Order> builder)
    {
        builder.HasOne<Product>()
               .WithMany()
               .HasForeignKey(c => c.ProductId);
    }

我在更新数据库时遇到的问题是 ProductId 字段不存在。这是因为它在表产品中命名为 Id,但在表顺序中它被命名为 ProductId。有没有办法用不同的名字映射外键?

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

    修改Product

    public class Product
    {
      public Guid? Id { get; set; }
      public string? Name { get; set; }
    
      public ICollection<Order> Orders {get; set;}
    }
    

    这种关系会正常运作。

    参考:Relationships

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-17
      • 2016-06-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多