0

I have two tables product and Images. They have a one-to-many relationship. I want to display product name and all its related images in the view, I am using repository pattern. I am new to MVC and Linq please help. Thanks in advance.

Here is my code....

public partial class tbl_Product
{
        public int pro_id { get; set; }
        public string pro_name { get; set; }
        public string pro_desc { get; set; }
        public string pro_model { get; set; }
        public string pro_dimensions { get; set; }
        public Nullable<int> pro_UnitsInStock { get; set; }
        public Nullable<double> pro_price { get; set; }
        public Nullable<double> pro_oldprice { get; set; }
  
        public virtual ICollection<tbl_Images> tbl_Images { get; set; }
}

ProductRepository class:

public ProductDetail GetProductByID(int id)
{
    var product = this.storeDB.tbl_Product.Where(x => x.pro_id == id).FirstOrDefault();   
                                      
    return product;
}

1 Answer 1

1

Just add an Include clause to load the related images:

public ProductDetail GetProductByID(int id)
{
    var product = storeDB.tbl_Product
                         .Where(x => x.pro_id == id)
                         .Include(p => p.tbl_Images)
                         .FirstOrDefault();   
                                      
    return product;
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot, now i am stuck at posting these values to the contoller method. Because var product cannot return ProductDetail.....please help
That's a whole new question - and if you do ask - please also post all relevant details (like definition of your ProductDetail class) so we stand a chance to actually help - thanks!
I have posted a new question regarding this issue. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.