asp.net - CodeFirst Foreign Key to two properties -
i'd use 1 property foreign key 2 seperate entities - once part of composite foreign key, , once single foreign key. here's quick example of mean:
public class parententity{ [key, column(order = 1)] string id {get; set;} [key, column(order = 2), foreignkey("year")] int yearid {get; set;} [foreignkey("yearid")] year year; virtual icollection<childentity> children {get; set;} } public class childentity{ [key, column(order = 0), foreignkey("parent")] string id {get; set;} [key, column(order = 1), foreignkey("parent")] string parentid {get; set;} [key, column(order = 2), foreignkey("parent, year")] int yearid {get; set;} [foreignkey("parentid, yearid")] parententity parent{get; set;} [foreignkey("yearid")] year year {get; set;} } public class year{ [key] int yearid {get; set;} } the yearid/year property in childentity should serve both part of primary key (parentid / year) parententity, , foreign key year table.
however, tag foreignkey("parent, year") not valid, because can take 1 parameter navigation property. error message get:
additional information: foreignkeyattribute on property 'yearid' on type 'codefirst.models.childentity' not valid. navigation property 'parent, year' not found on dependent type 'codefirst.models.childentity'. name value should valid navigation property name. which suppose makes sense, it's looking navigation property named 'parent, year' instead of 2 navigation properties, named 'parent' , 'year'.
how can force entityframework/codefirst recognise pattern correctly?
nb: named entities 'parent' / 'child', there no inheritance relation between them (it in fact ownership relation).
you need foreignkeyattribute on navigation property or foreign key property. not both. this:
public class parententity { [key, column(order = 1)] public string id { get; set; } [key, column(order = 2)] public int yearid { get; set; } [foreignkey("yearid")] year year; public virtual icollection<childentity> children { get; set; } } public class childentity { [key, column(order = 0)] public string id { get; set; } [key, column(order = 1)] public string parentid { get; set; } [key, column(order = 2)] public int yearid { get; set; } [foreignkey("parentid, yearid")] public parententity parent { get; set; } [foreignkey("yearid")] public year year { get; set; } } public class year { [key] public int yearid { get; set; } }
Comments
Post a Comment