2015-05-23 211 views
1

我正在使用實體框架來訪問數據庫並試圖在產品類中使用我的productModel類。但一些如何獲得轉換類型的錯誤。無法隱式轉換類型錯誤

錯誤:無法隱式轉換類型 'SporLife.Product' 到 'SporLife.Pages.Product'

這是我ManageProduct類

namespace SporLife.Pages.Management 
{ 
    public partial class ManageProduct : System.Web.UI.Page 
    { 
     private void FillPage(int id) 
     { 
      //set selected product from DB 
      ProductModel model = new ProductModel(); 
      Product product = model.GetProduct(id);//error appears here 

      //Fill textBoxes 
      txtDescription.Text = product.Description; 
      txtName.Text = product.Name; 
      txtPrice.Text = product.Price.ToString(); 
}}} 

這是我的產品型號類

namespace SporLife.Models 
{ 
    public class ProductModel 
    { 

    public Product GetProduct(int id) 
     { 
      try 
      { 
       using (SporLifeDBEntities2 db = new SporLifeDBEntities2()) 
       { 
        Product product = db.Products.First(i => i.ID == id); 
        return product; 

       } 
      } 
      catch (Exception e) 
      { 
       return null; 
      } 
     }}} 

回答

0

The這裏的問題是,return型方法的對象不匹配,你正在使用這個對象:

Product product = model.GetProduct(id);//error appears here 

你必須明確指定你希望它是這樣的,其對象:

SporLife.Product product = model.GetProduct(id); 

,並在你的方法一樣:

public SporLife.Product GetProduct(int id) 

我已經使用SporLife作爲一個例子。如果你想把SporLife.Pages作爲返回類型,你可以使用它。這裏的事情是在兩種情況下指定確切的返回類型,以便它們匹配。

希望這會有所幫助。

0

基本上有兩種不同類型的Product,SporLife.ProductSporLife.Pages.Productmodel.GetProduct(id)返回一個'SporLife.Product',所以如果沒問題的話,你需要改變調用代碼以期望。也許明確指定類型。

SporLife.Product product = model.GetProduct(id);//error appears here 
+0

SporLife.Pages.Product產物= SporLife.Models.ProductModel.GetProduct(ID); //這是課程的延伸。 –

+0

哪個產品做'db.Products' int GetProduct(int id)'方法返回? –

相關問題