从两个实体访问属性 [英] access attributes from two entities

查看:51
本文介绍了从两个实体访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了两个实体,它们具有导航属性.

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 };

如果我做

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

推荐答案

我怀疑您正在MVC视图中使用此视图,因此您需要为合并的用户和帐户对象创建视图模型,并在模型.

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 };

将列表作为模型传递.您的观点应为强类型. IEnumerable<UserAccountVM>应该可以工作.然后在您的视图中执行此操作:

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>
}

这篇关于从两个实体访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆