【问题标题】:Asp.net MVC and Entity Framework, Cannot access related tablesAsp.net MVC 和实体框架,无法访问相关表
【发布时间】:2009-05-18 12:54:15
【问题描述】:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/SiteControl.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Website.SimpleRepository.Page>>" %>

<asp:Content ID="Content2" ContentPlaceHolderID="content" runat="server">

<h2>Page List</h2>

  <p>
    <%= Html.ActionLink("Create New", "Create") %>
</p>

<table>
    <tr>
        <th></th>
        <th>
            Display As
        </th>
        <th>
            Layout
        </th>

    </tr>

<% foreach (var item in Model) { %>

    <tr>
        <td>
            <%= Html.Encode(item.DisplayAs) %>
        </td>
        <td>
            <%= Html.Encode(item.Types.Name) %>
        </td>
    </tr>

<% } %>

</table>
</asp:Content>

我很难访问 item.Types.Name 它返回一个空异常。我在一个单独的类库中有我的实体数据模型。谁能解释为什么它返回一个空异常以及我能做些什么来解决这个问题?我见过其他引用相关表值的项目,但无法弄清楚为什么我的工作有所不同......

任何关于这个主题的信息都会很棒!谢谢。

【问题讨论】:

  • 请在控制器操作中发送代码。

标签: asp.net-mvc entity-framework


【解决方案1】:

你是如何查询数据的?

我发现当前的 EF 设置要求我使用魔术字符串比我想要的更明确:

public IEnumerable<Item> GetItems(){
  ObjectQuery<Item> items = ItemSet.Include("Types");

  return (from i in items
          where [...]
          select i);
}

这当然不会让您在编译时检查外键,但它至少现在会返回它们。

【讨论】:

    【解决方案2】:

    确保实体映射中的外键关系允许延迟加载或这些引用属性。

    【讨论】:

      【解决方案3】:

      事实证明,正如我所料,我完全是新手。我的问题的解决方案是我没有将关联的表传递给视图。感谢您的回答!

      【讨论】:

        猜你喜欢
        • 2015-08-18
        • 2023-03-03
        • 2010-09-25
        • 2011-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多