【发布时间】:2013-06-25 09:50:18
【问题描述】:
我有以下用于我的数据库的类:
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; }
}
这是模型构建器:
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");
});
}
}
它按照我想要的方式设置关系,方式如下:
表:BaseProducts 列:ID、ProductName、Description、ImagePath、UnitPrice、CategoryID、Author
表:包 列:ID
表:产品 列:ID、Category_CategoryID
我想知道的是,为什么它会在 products 表中创建 Category_CategoryID 列?当我填充表格时,该列中的所有值都是空的,所以看起来它没有被用于任何事情。
此外,它似乎没有正确的关系 - 因为该类别上的 Products 虚拟集合始终为空。
【问题讨论】:
标签: c# asp.net entity-framework ef-code-first