[英]ASP.NET MVC 4 Joining two tables
please may you take a look at my code and point me in the right direction. 请你看看我的代码,并指出我正确的方向。 I have 2 tables : Product and vProductAndDescription.
我有2个表:Product和vProductAndDescription。 I need the Name and LisPrice from Product and the Description from vProductAndDescription joined by their ProductID respectively.
我需要Product中的Name和LisPrice以及分别通过其ProductID连接的vProductAndDescription的描述。 Am I on the right track at achieving this in my view?
在我看来,我是否正确地实现了这一目标? Because so far it is just crashing.
因为到目前为止它只是崩溃。
Controller: 控制器:
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());
}
View: 视图:
@{
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>
Your call var list = db.Database.SqlQuery<Product>(query);
你的调用
var list = db.Database.SqlQuery<Product>(query);
trying to create a List of type Product
but your actual query doesn't return a ProductID
parameter necessary to create the Product
type. 尝试创建类型为
Product
的List,但实际查询不返回创建Product
类型所需的ProductID
参数。 Also, what type are you expecting from the line 此外,您对该生产线的期望是什么类型
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
};
To start with, you need a ViewModel to hold your values in, because you aren't passing a whole existing object to your view. 首先,您需要一个ViewModel来保存您的值,因为您没有将整个现有对象传递给您的视图。
public class ProductDescriptionsViewModel {
public string Name {get;set;}
public string ListPrice {get;set;}
public string Description {get;set;}
}
in your View code at the top: 在顶部的View代码中:
@model IEnumerable<YourFullNamespace.ProductDescriptionsViewModel>
in your query you are actually making 2 calls on the database, let's see if we can re-arrange things to get one call: 在您的查询中,您实际上正在对数据库进行2次调用,让我们看看我们是否可以重新安排事情以获得一个调用:
string query = "SELECT v.Name as Name, p.ListPrice as ListPrice, LEFT(v.Description, 20) as Description from SalesLT.vProductAndDescription v, SalesLT.Product p WHERE v.ProductID = p.ProductID";
var viewModel = db.Database.SqlQuery<ProductDescriptionsViewModel>(query);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.