C#异常详细信息: System.NullReferenceException: 未将对象引用设置到对象的实例。

通过MVC 模板创建视图提示此类错误,

Model是通过引用EF6框架

控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Asset.Models;
        public ActionResult AssetList()
        {
            IList<UsbBorrow> UsbBorrows = null;
            using (AssetEntities db = new AssetEntities())
            {
                db.UsbBorrow.Select(S => S).ToList();
            }
            return View(UsbBorrows);
        }

视图代码

@model IEnumerable<Asset.Models.UsbBorrow>

@{
    ViewBag.Title = "AssetList";
}

<h2>AssetList</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Type)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Specification)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ProductName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Num)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ReceiveDate)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ReturnDate)
        </th>
        <th></th>
    </tr>

@foreach (Asset.Models.UsbBorrow UsbBorrow in Model ) {

    <tr>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.Type)
        </td>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.Specification)
        </td>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.ProductName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.Num)
        </td>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.ReceiveDate)
        </td>
        <td>
            @Html.DisplayFor(modelItem => UsbBorrow.ReturnDate)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id= UsbBorrow.ID }) |
            @Html.ActionLink("Details", "Details", new { id= UsbBorrow.ID }) |
            @Html.ActionLink("Delete", "Delete", new { id= UsbBorrow.ID })
        </td>
    </tr>
}

</table>

Foreach的时候报错

db.UsbBorrow.Select(S => S).ToList();
->
UsbBorrows = db.UsbBorrow.Select(S => S).ToList();

控制器代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Asset.Models;
public ActionResult AssetList()
{
IList UsbBorrows = null;
using (AssetEntities db = new AssetEntities())
{
UsbBorrows=db.UsbBorrow.Select(S => S).ToList();
}
return View(UsbBorrows);
}

因为你没有对UsbBorrows进行赋值,System.NullReferenceException都是由于调用了空对象的属性导致的。正确操作:
UsbBorrows = db.UsbBorrow.Select(S => S).ToList();