在视图中显示产品和相关图像,使用存储库模式 mvc 5

Display product and related images in the view, using repository pattern mvc 5

我正在尝试创建一个视图来显示产品信息及其相关图像。我正在使用存储库模式,

请看下面的代码,非常感谢你的帮助

public class ProductDetail
    {
        public int pro_id { get; set; }
        public string pro_name { get; set; }              
        public string pro_model { get; set; }
        public string pro_Dimensions { get; set; }            
        public string pro_imageTitle { get; set; }
        public string pro_image { get; set; }               
        public string pro_desc { get; set; }
        public Nullable<double> pro_price { get; set; }         
        public int pro_UnitsInStock { get; set; }
        public Nullable<double> pro_oldprice { get; set; } 
        public virtual ICollection<Images> tbl_Images { get; set; }

    }

 public class Images
    {
        public int ImageID { get; set; }
        public int productID { get; set; }
        public string ImageTitle { get; set; }
        public string ImagePath { get; set; }
    }

 public class ProductDetailRepository : IProductDetail
    {
        private readonly WebStoreEntities storeDB;

        public ProductDetailRepository() { }

        public ProductDetailRepository(WebStoreEntities _storeDB)
        {
            this.storeDB = _storeDB;
        }


public ProductDetail GetProductByID(int id)
        {
          
            var prod = storeDB.tbl_Product
                         .Where(x => x.pro_id == id)
                         .Include(p => p.tbl_Images)
                         .FirstOrDefault();
           
            return prod;  (Here it says, cannot implicitly convert type tbl_product to productdetail (this is where i need help))
        }

tbl_product 来自 EDMX 模型。 }

现在,我对这个方法很满意,我只想return将产品信息和相关图像发送到控制器,然后查看。

您基本上只需要将从数据库中获得的 tbl_Product 转换为您想要 return:

ProductDetail
public ProductDetail GetProductByID(int id)
{
    var prod = storeDB.tbl_Product
                      .Where(x => x.pro_id == id)
                      .Include(p => p.tbl_Images)
                      .FirstOrDefault();

    if (prod == null)
    {
        return null;
    }

    ProductDetail result = new ProductDetail
                               {
                                   // I'm just *GUESSING* here since you haven't showed
                                   // the tbl_product class, so I don't know what the 
                                   // properties on that class are called, really...
                                   pro_id = prod.Id,
                                   pro_name = prod.Name
                                   // and so on for all the properties
                               }

    return result;
}