对象引用未设置错误INSIDE!= null仅在块时?

时间:2009-12-31 18:11:59

标签: c# asp.net-mvc linq-to-sql

存储库代码:

public IQueryable<Bundle> getAllCustomBundlesByCompanyID(int companyID)
{
    return from companyBundle in db.CompanyBundles
           join bundle in db.Bundles on companyBundle.BundleID equals bundle.BundleID
           where companyBundle.CompanyID == companyID && bundle.CompanyID == companyID
           orderby bundle.BundleName ascending
           select bundle;
}

控制器代码:

    ViewData["OurCategories"] = bundleRepository.getAllCustomBundlesByCompanyID(CompanyID);

查看代码:

    <ul class="SmallCats">
       <%if(ViewData["OurCategories"] != null){ %>
            <%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>
            <%foreach(KODmvc.Models.Bundle b in ourCategories) { %>
            <li><a href="<%=b.BundleID%>">
                <img src="/Content/images/bundleicons/<%=b.BundleIcon %>" />
                <%=b.BundleName %></a>
            </li>
            <%} %>
        <%} else { %>
            There are no custom categories.
        <%} %>

    </ul>

ERROR:

 Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 38:                <%if(ViewData["OurCategories"] != null){ %>
Line 39:                     <%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>
Line 40:                     <%foreach(KODmvc.Models.Bundle b in ourCategories) { %>
Line 41:                     <li><a href="<%=b.BundleID%>">
Line 42:                         <img src="/Content/images/bundleicons/<%=b.BundleIcon %>" />


Source File: e:\Bancroft Archive\PanamaTrunk\Views\Asset\AdminDashboard.aspx    Line: 40 

但我正在检查以确保ViewData在放入之前不为空,究竟是什么?

3 个答案:

答案 0 :(得分:3)

好吧,如果as强制转换与您提供的类型不匹配,则返回null。您的foreach解除引用ourCategories,此时可能为空。

如果您不打算明确测试()为null,则应使用ourCategories强制转换。如果演员表失败,你将得到一个有意义的错误。

答案 1 :(得分:1)

getAllCustomBundlesByCompanyID不会返回List。

更改此行:

<%List<KODmvc.Models.Bundle> ourCategories = ViewData["OurCategories"] as List<KODmvc.Models.Bundle>; %>

对此:

<% var ourCategories = new List<KODmvc.Models.Bundle>(ViewData["OurCategories"] as IEnumerable<KODmvc.Models.Bundle>); %>

修改

如果你想保持懒惰的评估,你可以进一步简化代码。

<% foreach (var category in (IEnumerable<KODmvc.Models.Bundle>)ViewData["OurCategories"]) %>

答案 2 :(得分:0)

您的对象是IQueryable<KODmvc.Models.Bundle>,而不是List<KODmvc.Models.Bundle>

因此,表达式ViewData["OurCategories"] as List<KODmvc.Models.Bundle>将等于null。如果您将其更改为常规演员(List<KODmvc.Models.Bundle>)ViewData["OurCategories"],则会抛出InvalidCastException

要解决此问题,您需要更改控制器方法以在ToList上调用IQueryable,以便模型将保留List<KODmvc.Models.Bundle>,或将视图更改为强制转换为{ {1}}。