【问题标题】:display dynamic left outer join result in view在视图中显示动态左外连接结果
【发布时间】:2013-06-17 16:58:37
【问题描述】:

我正在 Entity Framework 中进行左外连接,并将输出发送到 ViewBag 以显示在表格中。但是,View 中不显示任何内容。我的代码如下。

        var clients = db.Client
                .Include("ClientInformation")
                .Where(t => t.IsApplicationRegistered == false)
                .Take(20);

        var q = (from c in clients
                join a in db.Agent
                on c.AgentUserId equals a.AgentUserId into jointable
                from x in jointable.DefaultIfEmpty()
                select new 
                { 
                    c.ClientId,
                    c.ClientInformation.FirstName,
                    c.ClientInformation.FamilyName,
                    c.ClientInformation.Address,
                    AgentFirstName = x.FirstName,
                    AgentLastName = x.LastName
                }).ToList();

        ViewBag.clients = q;

这会检索结果(我可以在调试期间通过 IntelliSense 看到它们)但视图不显示任何内容。示例视图如下。

@foreach (dynamic item in ViewBag.clients)
    {
        <tr>
            <td>@item.FirstName @item.FamilyName</td>
            <td>@item.Address</td>
            <td>@item.AgentFirstName @item.AgentLastName</td>
        </tr>
    }

有什么想法吗?谢谢。

更新:

View 里面我得到一个异常

'object' does not contain a definition for 'FirstName'

但是,当我将鼠标悬停在 foreach 循环内的 item 上时,我可以清楚地看到它在那里。

【问题讨论】:

    标签: asp.net-mvc entity-framework ef-code-first


    【解决方案1】:

    我的问题在这里得到了回答:dynamic type in mvc view

    您不能使用匿名类型作为模型。原因是编译器将匿名类型作为内部发出。这意味着它们只能通过当前程序集访问。但正如您所知,Razor 视图由 ASP.NET 运行时编译为单独的程序集,无法使用这些匿名类型。

    显然在这种情况下正确的方法是使用视图模型。

    所以,我将只使用视图模型。

    更多关于这方面的信息在这里:Dynamic Anonymous type in Razor causes RuntimeBinderException

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-21
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多