【问题标题】:How to make foreign key inside models for particular column of composite primary key in Entity Framework如何在实体框架中为复合主键的特定列创建外键
【发布时间】:2019-09-07 05:49:02
【问题描述】:
class1
{
    [key]
    public string id1 {get; set;}

    [Key]
    public string key2 {get; set;}
}

class2
{
    [foreignKey("class1")]
    public string class1Id{ get; set; }
}

现在在class2 内部,我只想使用class1id1 列作为外键。

怎么做?

【问题讨论】:

  • 这似乎与 ASP.NET 无关。
  • 你不能。 FK 只能指向被引用表中的 unique 列(主键或备用键)。

标签: c# entity-framework entity-framework-core code-first entity-framework-migrations


【解决方案1】:

如果您更喜欢数据注释,只需在导航属性上应用 ForeignKey 属性,并提供一个带有 FK 属性名称的逗号分隔列表

 class1{
    [key]
    public string id1 {get; set;}

    [Key]
    public string key2 {get; set;}
    }

    class2{

    public string id1 { get; set;}

    public string key2 { get; set;}

      [ForeignKey("id1,key2")] // <= the composite FK
      public virtual class1 class1{ get; set; }

    }

使用流畅的 API 配置更容易理解且不易出错:

modelBuilder.Entity< class2>()
    .HasRequired(e => e. class1) 
    .HasForeignKey(e => new { e.id1, e.key2 });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 2012-03-26
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多