Entity Framework Issue with connecting more than one table
I got products table
product table
->productID - primary
->price
->Quantity
productCategory -table
->prodcatID- primary
->productId - foreign key
->categoryID - foreign key
productlanguages - table
->productLanguages - primary
->productID - foreign key
->languageID - forein key
->Title
So I should use Entity framework and I should somehow get all products WITH THEIR TITLE,QUANTITY AND PRICE From GIVEN CATEGORY AND FROM GIVEN LANGUAGE . SO i should somehow combine info from all these three table
SO i started with thisuery
var lst = db.ProuctCategories.Where(x=>x.CategoryID==catID).ToList();
and get all products from single category -> but now I HAVE NOACCESS TO PRODUCTLANGUAGE TABLE and I cannot filter by language.
If I start with
var lst = db.ProductLanguages.Where(x=>x.LanguageID==langID).ToList();
Now I have no access to productCategories.
And I've been thinking that for hours and I can't find a way to connect productlanguages and productcategories.
Is there a requirement for you to have a separate Id on productCategory and productLanguages entities? If not, I would implement it this way:
public class Product
{
[Key]
public int Id { get; set; }
public int Price{ get; set; }
public int Qty{ get; set; }
public virtual List<Category> Categories{ get; set; }
public virtual List<Language> Languages{ get; set; }
}
public class Category
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
public virtual List<Product> Products{ get; set; }
}
public class Language
{
[Key]
public int Id { get; set; }
public string Description { get; set; }
public virtual List<Product> Products{ get; set; }
}
and then define the many-to-many relationships while overriding the OnModelCreating method
modelBuilder.Entity<Product>().HasMany(p => p.Categories).WithMany(c => c.Products).Map(m => { m.MapLeftKey("ProductId"); m.MapRightKey("CategoryId"); m.ToTable("ProductCategories"); });
modelBuilder.Entity<Product>().HasMany(p => p.Languages).WithMany(l => l.Products).Map(m => { m.MapLeftKey("ProductId"); m.MapRightKey("LanguageId"); m.ToTable("ProductLanguages"); });
This way, the virtual properties should allow you to navigate through the entities and their relations.
Please let me know if you resolve your issue.
链接地址: http://www.djcxy.com/p/6394.html上一篇: 语言支持而不改变数据库结构
下一篇: 连接多个表的实体框架问题