MVC5中展示LINQ关联两表生成的列表出现报错该如何解决?
问题背景
- 本次开发涉及两张数据表:
- 商品信息表(item info):包含
item ID(商品ID)、item name(商品名称)、price(价格)三个字段 - 商品佣金表(item commission):包含
commission ID(佣金ID)、item ID(商品ID)、rate of commission(佣金比例)三个字段
- 商品信息表(item info):包含
- 需求为在视图中展示商品信息表的商品名称、商品佣金表的佣金比例,通过LINQ关联两张表查询生成结果列表后,在MVC5视图中渲染时报错
现有视图代码
@model IEnumerable<FRANCHISEE.Models.FrcItemList> @{ ViewBag.Title = "FranchiseeItemList"; } <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.ItemName) </th> <th> @Html.DisplayNameFor(model => model.Roc) </th> <th> @Html.DisplayNameFor(model => model.FrcItemId) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.ItemName) </td> <td> @Html.DisplayFor(modelItem => item.Roc) </td> <td> @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) | @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ }) </td> </tr> }
常见报错原因及修复方案
绝大多数此类报错由以下三类问题导致,可逐一排查:
- ViewModel定义不匹配
视图绑定的是IEnumerable<FRANCHISEE.Models.FrcItemList>,需先确认FrcItemList类包含视图中用到的ItemName、Roc、FrcItemId三个公共属性,缺失则补全即可:
public class FrcItemList { public int FrcItemId { get; set; } // 对应商品ID,作为主键 public string ItemName { get; set; } // 对应商品名称 public decimal Roc { get; set; } // 对应佣金比例 }
- LINQ查询返回值类型不匹配
关联查询必须返回IEnumerable<FrcItemList>类型才能和视图绑定匹配,示例关联查询写法参考:
var result = from item in db.item_info join comm in db.item_commission on item.item_ID equals comm.item_ID select new FrcItemList { FrcItemId = item.item_ID, ItemName = item.item_name, Roc = comm.rate_of_commission }; return View(result.ToList());
- 空值传递报错
查询结果为空时直接返回视图,Model为null会触发遍历报错,需要在Action返回前做空值处理,或者在视图中加判空逻辑:
@if(Model == null || !Model.Any()) { <p>暂无匹配的商品数据</p> } else { // 原有表格渲染逻辑放在此处 }
内容的提问来源于stack exchange,提问作者Rima Das
相关产品推荐
相关产品推荐

