0

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.

4

2 回答 2

0

您可能需要将 CategoryID 重命名为 CategoryId,以便 EF 可以将其识别为 Category 实体的关键字段。

于 2013-06-25T10:29:26.117 回答
0

我想到了!类别中的虚拟 ICollection 是 Product 类型,而实际上它应该是 BaseProduct。

有意义的是,当 Product 仅具有该类型的引用时,它会获得一个额外的列来引用 Category。

于 2013-06-25T22:03:33.487 回答