简体   繁体   English

如何在Entity Framework中为复合主键的特定列创建外键模型

[英]How to make foreign key inside models for particular column of composite primary key in Entity Framework

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

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

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

Now here inside class2 I want to use only id1 column of class1 as foreign key. 现在在class2里面我想只使用class1 id1列作为外键。

How to do that? 怎么做?

If you prefer data annotations, just apply the ForeignKey attribute on the navigation property and provide a comma separated list with the FK property name 如果您更喜欢数据注释,只需在导航属性上应用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; }

    }

using fluent API configuration is much easier to understand and less error prone: 使用流畅的API配置更容易理解,更不容易出错:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架-具有主键和复合外键的多对多 - Entity Framework - many to many with primary key and composite foreign key Entity Framework 5.0非主键的复合外键-可能吗? - Entity Framework 5.0 composite foreign key to non primary key - is it possible? 如何在Entity Framework中基于2个外键制作复合键? - How to make composite key based on 2 foreign keys in Entity Framework? 实体框架-由3个外键组成的复合主键 - Entity Framework - Composite Primary Key formed by 3 Foreign Keys Entity Framework Core - 复合键和外键作为主键 - Entity Framework Core - Composite and Foreign Keys as Primary Key 如何使用主键-实体框架获取列的特定值? - How to get the particular value of column using the primary key - entity framework? 如何在Entity Framework中创建由外键组成的复合主键? - How can I create a composite primary key consisting of foreign keys to two tables in Entity Framework? 实体框架:外键作为组合键的一部分 - Entity Framework:Foreign Key as part of Composite key Entity Framework Core:使用自动生成的外键作为复合主键的一部分 - Entity Framework Core: use auto-generated foreign key as part of composite primary key 在Code-First Entity Framework中包含复合主键中的外键 - Include foreign key in composite primary key in Code-First Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM