I have the following classes that I use for my database:
public abstract class BaseProduct
{
public int ID { get; set; }
[Required, StringLength(100), Display(Name = "Name")]
public string ProductName { get; set; }
[Required, StringLength(10000), Display(Name = "Product Description"), DataType(DataType.MultilineText)]
public string Description { get; set; }
public string ImagePath { get; set; }
[Display(Name = "Price")]
public double? UnitPrice { get; set; }
public int? CategoryID { get; set; }
public virtual Category Category { get; set; }
public string Author { get; set; }
public virtual ICollection<PriceRelation> Prices { get; set; }
}
[Table("Packages")]
public class Package : BaseProduct
{
public virtual ICollection<Product> Products { get; set; }
}
[Table("Products")]
public class Product : BaseProduct
{
public virtual ICollection<Package> Packages { get; set; }
}
public class Category
{
[ScaffoldColumn(false)]
public int CategoryId { get; set; }
[Required, StringLength(100), Display(Name = "Name")]
public string CategoryName { get; set; }
[Display(Name = "Category Description")]
public string Description { get; set; }
public int? ParentID { get; set; }
[ForeignKey("ParentID")]
public virtual Category Parent { get; set; }
public virtual ICollection<Category> Children { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
And this is the model builder:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Package>().HasMany(p => p.Products).WithMany(p => p.Packages)
.Map(m =>
{
m.ToTable("PackageRelations");
m.MapLeftKey("PackageID");
m.MapRightKey("ProductID");
});
}
}
It sets up the relations as I want to, in the following way:
Table: BaseProducts Columns: ID, ProductName, Description, ImagePath, UnitPrice, CategoryID, Author
Table: Packages Columns: ID
Table: Products Columns: ID, Category_CategoryID
The thing I'm wondering is, why does it create the column Category_CategoryID in the products table? When I populate the table, all the values in this column are null, so it doesn't look like it's being used for anything.
Also, it doesn't seem to have the relations right - because the virtual collection of Products on the category is always empty.