[英]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; }
}
现在在class2
里面我想只使用class1
id1
列作为外键。
怎么做?
如果您更喜欢数据注释,只需在导航属性上应用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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.