c# - How to define a table that its primary key is constructed from 2 foreign keys with EF code-first -
i using models define tables using ef code-first.
i have , item model , order model.
item:
public class item { public int itemid { get; set; } [required] public int price { get; set; } [required] public int amountleft { get; set; } [required] public string image { get; set; } [required] public string description { get; set; } [required] public string fulldescription { get; set; } [required] public datetime publishdate { get; set; } public int companyid { get; set; } public int categoryid { get; set; } // navigation properties public virtual company company { get; set; } // navigation properties public virtual category category { get; set; } }
order model:
public class order { public int orderid { get; set; } [required] public datetime deliverydate { get; set; } [required] public string currency { get; set; } [required] public int totalamount { get; set; } public list<int> items { get; set; } public datetime orderdate { get; set; } public int userid { get; set; } // navigation properties public virtual user user { get; set; } }
i want create table called iteminorder have 2 fields: itemid , orderid. primary key these 2 foreign keys.
i tried define model:
public class iteminorder { public int orderid { get; set; } public int itemid { get; set; } // navigation properties public virtual order order { get; set; } public virtual item item { get; set; } }
but got errors. tried put [key] notation on both fields still got errors.
how able create table want?
when need create table composite pks, need specify order of keys. there 2 variants:
you override onmodelcreating
method on context, , try these fluent api configurations:
// configure primary keys iteminorder in order want modelbuilder.entity<iteminorder>() .haskey(t => new{t.orderid,itemid); modelbuilder.entity<iteminorder>() .hasrequired(io=>io.order) .withmany() .hasforeigkey(io=>io.orderid); modelbuilder.entity<iteminorder>() .hasrequired(io=>io.item) .withmany() .hasforeigkey(io=>io.itemid);
the second variant using data annotations should way:
[key] [column(order=1)] [foreignkey("order")] public int orderid { get; set; } [key] [column(order=2)] [foreignkey("item")] public int itemid { get; set; }
ef notice want create 2 relationships , job you.
Comments
Post a Comment