access attributes from two entities

2019-09-02 06:29发布

问题:

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");