access attributes from two entities

2019-09-02 07:02发布

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

3条回答
孤傲高冷的网名
2楼-- · 2019-09-02 07:20

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>
}  
查看更多
Fickle 薄情
3楼-- · 2019-09-02 07:24

Try including the related objects.

e.g.

var list = storeDB.Users.Include("Accounts");
查看更多
Animai°情兽
4楼-- · 2019-09-02 07:30

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>
}
查看更多
登录 后发表回答