2013-08-05 28 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