asp.net mvc 3 - Entity Framework: M-to-n: Read a linked entity from a list -
asp.net mvc 3 - Entity Framework: M-to-n: Read a linked entity from a list -
i know title isn't quite specific , i'm sure question has been asked somewhere don't know how search it.
i'm using asp.net mvc entity framework , have next model:
public class receipt { public int receiptid { get; set; } public bool deleted { get; set; } public int useraccountid { get; set; } public int messageid { get; set; } public virtual useraccount useraccount { get; set; } public virtual message message { get; set; } }//end receipt a user has several receipts. messages specific user.
this how i'm doing far:
//get receipts of logged in user list<receipt> receipts = unitofwork.receiptrepository.get( u => u.useraccountid == loggedinuser.useraccountid).tolist<receipt>(); //get messages of receipts list<message> messages = new list<message>(); foreach (receipt receipt in receipts) { messages.add(receipt.message); } is there improve way?
thanks in advance.
do have link message receipt? i'm assuming receipt class has one-to-one relationship message class. able method, message class should this:
public class message { public int messageid {get; set;} //other properties here //these provide backward link receipt "owns" message public int receiptid {get; set;} public virtual receipt receipt {get; set;} } your model should recognize link having (if using code first)
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<receipt>() .hasoptional(r => r.message) .withrequired(m => m.receipt); } your query should done @ repository level, message repository because layer has access database context. query this:
public ienumerable<message> getallmessagesbyuserid (int userid) { homecoming context.set<message>().include(x => x.receipt) .include (x => x.receipt.useraccount) .where (x => x.receipt.useraccount.useraccountid == userid) .tolist(); } when phone call unitofwork.messagerepository.getallmessagesbyuserid (loggedinuser.useraccountid), should homecoming messages linked user interested in.
asp.net-mvc-3 linq entity-framework
Comments
Post a Comment