c# - Entity Framework - Relationships -
i looking create currency
, crossrates
in entity framework.
from sql perspective crossrates
table quite simple.
date |fromcurrency|tocurrency|rate 01/01/2000|usd |eur |1.5 01/01/2000|eur |usd |0.67
how take above idea , apply within entity framework?
here have far...
public class currency { public int id { get; set; } public string name { get; set; } //navigation public virtual list<crossrate> crossrates { get; set; } } public class crossrate { public int fromcurrencyid {get;set;} public int tocurrencyid {get;set;} public datetime date {get;set;} public decimal rate {get;set;} }
i think need create 2 one-to-many relationships, currency
must have 2 collection of crossrate
. can't have single collection referenced 2 fks, unless pk of entity composite (like in post), currency
have 1 pk. try model:
public class currency { public int id { get; set; } public string name { get; set; } //navigation prop, these crossrates currency used public virtual icollection<crossrate> fromcrossrates { get; set; } //navigation prop, these crossrates currency used public virtual icollection<crossrate> tocrossrates { get; set; } } public class crossrate { public int fromcurrencyid { get; set; } public int tocurrencyid { get; set; } public datetime date { get; set; } public decimal rate { get; set; } public currency fromcurrency { get; set; } public currency tocurrency { get; set; } }
and relationships configuration be:
//composite pks of croassrate entity modelbuilder.entity<crossrate>().haskey(cr => new {cr.fromcurrencyid, cr.tocurrencyid}); //one-to-many modelbuilder.entity<crossrate>() .hasrequired(s => s.fromcurrency) .withmany(s => s.fromcrossrates) .hasforeignkey(s => new { s.fromcurrencyid }); modelbuilder.entity<crossrate>() .hasrequired(s => s.tocurrency) .withmany(s => s.tocrossrates) .hasforeignkey(s => new { s.tocurrencyid });
Comments
Post a Comment