在MVC3中为三个表创建模型的问题 [英] Problem with creating model for three tables in MVC3
问题描述
大家好,
我在MVC 3中遇到一些困难.我真的是MVC 3的新手.现在,我正在开发示例电子商务网站.这是我展示商品的模型.
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; }
}
但我不知道如何与ProductPhoto表连接.请帮助我.
最佳Rgds,
df
but i don''t know how to connect with ProductPhoto table. Pls help me.
Best Rgds,
df
推荐答案
使用实体框架代码优先"尝试此模型...
Try with this model using Entity Framework Code First...
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
}
然后使用 DbSet< Category>设置您的DbContext.类别,DbSet< Product>产品,DbSet< ProductPhoto>产品照片.如果您不使用JSON序列化,则可以轻松忽略[JsonIgnore]属性.
使用此查询可根据类别从产品"中检索图像.我仅检索第一个产品的图像.
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.
这篇关于在MVC3中为三个表创建模型的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!