现在刚开始看asp.net mvc2做了个demo,用的是northwind数据库
代码如下:
CategoriesRepository.csList<Categories> ICategories.FindAllCategory()
{
    var result = db.Categories.Select(c => new Categories
   {
        CategoryID = c.CategoryID,
        CategoryName = c.CategoryName
   });
   return result.ToList<Categories>();
}
CategoryControllers
public ActionResult Index()
{
    return View(_categoriesRepository.FindAllCategory());
}
VIEW使用的是强类型 Categories类
   <% foreach (var item in Model)
       { %>
    
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id=item.CategoryID }) %> |
                <%: Html.ActionLink("Details", "Details", new { id=item.CategoryID })%> |
                <%: Html.ActionLink("Delete", "Delete", new { id=item.CategoryID })%>
            </td>
            <td>
                <%: item.CategoryID %>
            </td>
            <td>
                <%: item.CategoryName %>
            </td>
            <td>
                <%: item.Description %>
            </td>
        </tr>
    
    <% } %>Debug的时候报错:“未将对象引用设置到对象的实例”。
麻烦各位帮忙找下原因,谢谢

解决方案 »

  1.   

    CategoriesRepository.csList<Categories> ICategories.FindAllCategory()
    {
      var result = db.Categories.Select(c => new Categories
      {
      CategoryID = c.CategoryID,
      CategoryName = c.CategoryName
      });
      return result.ToList<Categories>();
    }要么改成List<Categories> ICategories.FindAllCategory()
    {
      var result = db.Categories.Select(i=>i);
      return result.ToList<Categories>();
    }要么单独建一个视图模型来承载你查找的匿名对象
      

  2.   

    var result = db.Categories;这样就可以了没必要后面的了
      

  3.   

    如果一个实例对象有很多属性,我不想全部显示出来,肯定要new一个的嘛
      

  4.   

    你在View里用了item.Description,但你选择的数据源里却没有:
    var result = db.Categories.Select(c => new Categories
      {
      CategoryID = c.CategoryID,
      CategoryName = c.CategoryName,
      Description=c.Description
      });
    即可