access attributes from two entities

試著忘記壹切 提交于 2019-12-25 03:48:10

问题


I created two entities and they have navigation properties.

 var list = from u in storeDB.Users
            join a in storeDB.Accounts
            on u.Id equals a.Id
            select new { u, a };

if I do a

foreach( user in list){
   <span>user.Name, user.Money</span>
}

It does not work. My question is how can I display the content from the result attributes of both tables, that is, of the join??

Users: has Name, Id
Accounts: has Id, Money

回答1:


I suspect you are using this in an MVC view so you need to create a view model for your combined user and account objects and send an Enumerable of it at the model.

public class UserAccountVM{
    public Account Acct { get; set; }
    public User Usr { get; set; }
}

Then in your query do this:

var list = from u in storeDB.Users            
           join a in storeDB.Accounts            
           on u.Id equals a.Id            
           select new UserAccountVM { Usr = u, Acct = a };

Pass the list as your model. Your view should be strongly typed; IEnumerable<UserAccountVM> should work. Then do this in your view:

foreach( user in list){   
    <span>user.Usr.Name, user.Acct.Money</span>
}



回答2:


The properties on the anonymous object are u and a as you've named them. You probably want to give them better names or, better yet, simply select the properties you are interested in. I would give them explicit names, but you could omit that if the names you want are the same as the property names and there aren't any conflicts.

var list = from u in storeDB.Users
           join a in storeDB.Accounts
           on u.Id equals a.Id
           select new { Name = u.Name, Money = a.Money };

Then use them as

foreach( user in list){
     <span>user.Name, user.Money</span>
}  



回答3:


Try including the related objects.

e.g.

var list = storeDB.Users.Include("Accounts");


来源:https://stackoverflow.com/questions/5411829/access-attributes-from-two-entities

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!