2017-04-21 113 views
0

我收到一條錯誤消息,內容如下: 「映射不存在於對象類型<> f__AnonymousType6`1 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]到已知的託管提供程序本機類型「。ASP.NET MVC數據倉庫

public List<Product> GetCategoryProducts(int catID) 
     { 
      string sql = @"select p.ProductID, p.ItemName, p.ImageName 
          from Product p, ProductCategory pc 
          where p.ProductID = pc.ProductID 
          and pc.CategoryID = @catID 
          order by p.ItemName"; 


      List<Product> products = db.Products.SqlQuery(sql, new { catID }).ToList(); 
      return products; 

     } 

我不知道爲什麼我收到此錯誤

+0

它在'SqlQuery'方法幫助中解釋。但是爲什麼還要用SQL呢,這是很簡單的LINQ To Entities查詢,你沒有使用ORM的好處。 –

+2

請不要刪除以前的問題並將其更改爲新的問題。要麼創建一個新問題,要麼編輯你的問題以包含附加問題信息(離開舊問題)。通過刪除該問題,您可以防止其他人從您的問題中獲益。這也令人困惑,爲什麼有些答案似乎無法解決當前的問題。 –

回答

2

你應該做兩件事一)改變你的查詢,SqlQuery<Product>B的返回類型)傳遞參數catID到您的查詢:

var products = db.Products 
       .SqlQuery<Product>(sql,new SqlParameter("catID", catID)) 
       .ToList(); 

I am setting pc.CategoryID = @catID.

你的確聲明參數化查詢,但是你不會爲你的參數傳遞一個值。以下只是一個字符串:

@"select p.ProductID, p.ItemName, p.ImageName 
from Product p, ProductCategory pc 
where p.ProductID = pc.ProductID 
and pc.CategoryID = @catID 
order by p.ItemName" 

你不設置那裏爲CategoryID任何價值。這是SqlQuery方法的工作,只要你通過一個就可以處理這個問題。

+0

我添加了列表 products = db.Products.SqlQuery(sql,new {catID})。ToList(); 修復標量變量錯誤 –

+0

現在我得到這個錯誤:沒有從對象類型<> f__AnonymousType6'1 [[System.Int32,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]的映射到已知的託管提供商本機類型 –

+0

@TimothyWong請檢查我的更新。 – Christos