Click here to Skip to main content
15,883,922 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi All,

I face some difficulties in MVC 3. I am really newbie in MVC 3. now i am developing sample ecommerce website. this is my models for displaying goods.

public class Product{
   public int productid {get;set;}
   public int CatID {get;set;}
   public string productname {get;set;}
   public string description {get;set;}
}

public class ProductPhoto{
   public int ProductPhotoID {get;set;}
   public int Productid {get;set;}
   public string Photopath {get;set;}
}

public class Category{
   public int CatID {get;set;}
   public string CatName {get;set;}
}


i want to show the products with picture depend on category in product
display page. So i build model like following.
public partial class Genre
   {
       public int CatID { get; set; }
       public string CatName { get; set; }
       public List<Product> Products { get; set; }
   }


but i don't know how to connect with ProductPhoto table. Pls help me.

Best Rgds,
df
Posted

1 solution

Try with this model using Entity Framework Code First...

C#
public class Product{
   public int productid {get;set;}
   public int catID {get;set;}
   public string productname {get;set;}
   public string description {get;set;}

   [ForeignKey("catID")]
   public virtual Category ProductCategory
   [JsonIgnore]
   public virtual ICollection<ProductPhoto> Photos
}

public class ProductPhoto{
   public int ProductPhotoID {get;set;}
   public int Productid {get;set;}
   public string Photopath {get;set;}

   [ForeignKey("Productid")]
   public virtual Product ProductOwner
}

public class Category{
   public int CatID {get;set;}
   public string CatName {get;set;}
   [JsonIgnore]
   public virtual ICollection<Product> Products
}


Then set your DbContext using DbSet<Category> Categories, DbSet<Product> Products, DbSet<ProductPhoto> ProductPhotos. If you are not using JSON serialization you can easily ignore [JsonIgnore] attribute.

Use this query to retieve images from Product based on category. I am retrieving the images of the first product only.
var v = dbContext.Products.Where(p=>p.catID == suppliedCatgoryId).First();
var images = v.Photos

Let me know if this helps.
 
Share this answer
 
Comments
dartfrog 7-Sep-12 5:06am    
Ok .. but now i use linq to sql classes how should i do ?

Genre gen = from prd in db.Products
join prdphoto in db.ProductPhotos on prd.productid equals prdphoto.productid
join cat in db.Categories on prd.CatID equals cat.CatID
where cat.CatName==categoryName

i don't know how to write "select" statement for Genre class.
ray_mayukh 12-Sep-12 7:57am    
var v = from p in dbContext.Products

where p.catID == suppliedCatgoryId

select new{
photos = p.Photos
};

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900