I'm using Entity Framework code first approach to create mydatabase. I've got four simple classes:
My first class is Category:
public class Category
{
[Key]
public int CategoryId { set; get; }
public DateTime CreatedOn { set; get; }
public int? ParentCategoryId { set; get; }
public virtual ICollection<Product> Products { set; get; }
public virtual ICollection<CategoryLanguage> CategoriesLanguages { set; get; }
public Category()
{
this.Products = new HashSet<Product>();
this.CategoriesLanguages = new HashSet<CategoryLanguage>();
}
}
My Second class -CategoryLanguage.cs
public class CategoryLanguage
{
[Key]
public int Id { set; get; }
[Required]
public string Title { set; get; }
public int CategoryId { set; get; }
public virtual Category Category { set; get; }
public int LanguageId { set; get; }
public virtual Language Language { set; get; }
}
My third class - Product.cs
public class Product
{
[Key]
public int ProductId { set; get; }
public decimal Price { set; get; }
public int Quantity { set; get; }
public string Image { set; get; }
public virtual ICollection<Category> Categories { set; get; }
public virtual ICollection<ProductLanguage> ProductLanguages { set; get; }
public Product()
{
this.Categories = new HashSet<Category>();
this.ProductLanguages = new HashSet<ProductLanguage>();
}
}
and my last class
public class ProductLanguage
{
[Key]
public int Id { set; get; }
public int ProductId { set; get; }
public virtual Product Product { set; get; }
public int LanguageId { set; get; }
public virtual Language Language { get; get; }
public string Name { set; get; }
public string ShortDescription { set; get; }
public string Description { set; get; }
}
Here is my DbContext
public class EcommerceDBContext:DbContext
{
public EcommerceDBContext() : base("DefaultConnection"){}
public DbSet<Category> Categories { set; get; }
public DbSet<CategoryLanguage> CategoriesLanguages { set; get; }
public DbSet<Product> Products { set; get; }
public DbSet<ProductLanguage> ProductsLanguages { set; get; }
}
It's curious that in my database I see another table, ProductCategories with two columns: Product_ProductID and Category_CategoryID.
So it's true that Product table and Categories table have many-to-many relationship and it's also true that I'm using lazy loading to be able to load all the products for Category; and all the categories for product. I'm just curious how code-first engine decides to make this table. (after all the collections are virtual and they should not exist in the database).