请你看看我的代码并指向正确的方向。 我有2个表格:产品和vProductAndDescription。我需要产品的Name和LisPrice以及分别通过ProductID添加的vProductAndDescription的描述。在我看来,我在正确的轨道上实现这一目标吗?因为到目前为止它只是崩溃。ASP.NET MVC 4加入两张表
控制器:
public ActionResult Index()
{
string query = "SELECT v.Name, p.ListPrice, LEFT(v.Description, 20) from SalesLT.vProductAndDescription v, SalesLT.Product p WHERE v.ProductID = p.ProductID";
var list = db.Database.SqlQuery<Product>(query);
var result = from a in list.ToList()
join b in db.vProductAndDescriptions on a.ProductID equals b.ProductID
select new
{
c = a.Name,
d = a.ListPrice,
e = b.Description
};
return View(result.ToList());
}
查看:
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table>
<tr>
<th>Name
</th>
<th>Price (R)
</th>
<th>Description
</th>
<th></th>
</tr>
@foreach (var item in ViewData.Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.ListPrice)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</table>
你会得到什么错误? – Stijn
EntityCommandExecutionException未被用户代码处理,数据读取器与指定的“AdventureWorksLT2008R2Model.Product”不兼容。类型为'ProductID'的成员在数据读取器中没有相应的列,名称相同。 – Chris
这对我来说完全没有意义,因为它显然确实有相应的列,这很明显。当然有一种更简单的方法来连接两个表并在视图中显示它们? – Chris