2013-08-05 24 views
0

请你看看我的代码并指向正确的方向。 我有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> 
+0

你会得到什么错误? – Stijn

+0

EntityCommandExecutionException未被用户代码处理,数据读取器与指定的“AdventureWorksLT2008R2Model.Product”不兼容。类型为'ProductID'的成员在数据读取器中没有相应的列,名称相同。 – Chris

+0

这对我来说完全没有意义,因为它显然确实有相应的列,这很明显。当然有一种更简单的方法来连接两个表并在视图中显示它们? – Chris

回答

2

您的通话var list = db.Database.SqlQuery<Product>(query);努力创造Product类型的列表,但实际查询不返回所需的ProductID参数创建Product类型。此外,你从线

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 
       }; 

首先期待什么类型的,你需要一个ViewModel在牵你的价值,因为你不通过一个整体存在的对象到您的视图。

public class ProductDescriptionsViewModel { 
    public string Name {get;set;} 
    public string ListPrice {get;set;} 
    public string Description {get;set;} 
} 
在顶部您查看代码

@model IEnumerable<YourFullNamespace.ProductDescriptionsViewModel> 
在查询你实际上是在数据库上做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); 
+0

我试图用一个原始的sql查询来做到这一点,因为我只需要Name,ListPrice和前20个字的描述。 – Chris

+0

我试图找出一种方法来说明需要对您的代码进行哪些更改,并且我确定我们可以计算出如何使用原始的sql调用。 – Claies

+0

我已经有了上面建议的viewmodel,它需要包含ProductID,否则var结果的a.ProductID部分将不起作用。我收到了一些奇怪的错误。错误:传入字典的模型项目类型为'System.Collections.Generic.List'1 [<> f__AnonymousType4'3 [System.String,System.Decimal,System.String]]',但是此字典需要一个模型“System.Collections.Generic.IEnumerable'1 [AW_Internet.Models.ProdList]'类型的项目。编辑 – Chris