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.
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
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:
modelBuilder.Entity< class2>()
.HasRequired(e => e. class1)
.HasForeignKey(e => new { e.id1, e.key2 });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.