【发布时间】:2015-07-16 17:49:10
【问题描述】:
我有一个包含相关产品列表的产品类别。
例如:
产品 = 星球大战
AssociatedProducts = 第五集:帝国反击,第六集:绝地归来,第七集:原力觉醒
但 EF 生成的数据库带有一些额外的列。
这是我的产品类别:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public string ShortDescription { get; set; }
public string FullDescription { get; set; }
public decimal UnitPrice { get; set; }
......
public virtual ICollection<AssociatedProducts> AssociatedProducts { get; set; }
......
}
这是我的 AssociatedProduct 类:
public class AssociatedProducts
{
public int Id { get; set; }
public int ProductId { get; set; }
public int AssociatedProductId { get; set; }
public int DisplayOrder { get; set; }
public DateTime CreatedOn { get; set; }
public virtual Product Products { get; set; }
public virtual Product AssociatedProductsId { get; set; }
}
这是我对 AssociatedProduct 类的映射:
public AssociatedProductsMap()
{
// Primary Key
HasKey(a => a.Id);
// Properties
Property(a => a.CreatedOn).IsRequired();
Property(a => a.ProductId).IsRequired();
Property(a => a.AssociatedProductId).IsRequired();
Property(a => a.DisplayOrder).IsRequired();
//Relationship
HasRequired(a => a.Products)
.WithMany(p => p.Products)
.HasForeignKey(a => a.ProductId)
.WillCascadeOnDelete(false);
HasRequired(a => a.AssociatedProductsId)
.WithMany(p => p.AssociatedProducts)
.HasForeignKey(a => a.AssociatedProductId)
.WillCascadeOnDelete(false);
//Table
ToTable("AssociatedProducts");
}
这就是我播种的方式:
var associetedProducts = new List<AssociatedProducts>
{
new AssociatedProducts {ProductId= 1, AssociatedProductId = 3, DisplayOrder = 1, CreatedOn = DateTime.Now},
new AssociatedProducts {ProductId= 1, AssociatedProductId = 4, DisplayOrder = 2, CreatedOn = DateTime.Now},
new AssociatedProducts {ProductId= 1, AssociatedProductId = 5, DisplayOrder = 3, CreatedOn = DateTime.Now}
}
new List<Product>
{
new Product {Name = "StarWar", ShortDescription = "...", FullDescription = "P.......", UnitPrice = 15m, AssociatedProducts = associetedProducts},
new Product {Name = "StarWar Episode V", ShortDescription = "...", FullDescription = "P.......", UnitPrice = 15m},
new Product {Name = "StarWar Episode VI", ShortDescription = "...", FullDescription = "P.......", UnitPrice = 15m},
new Product {Name = "StarWar Episode VII", ShortDescription = "...", FullDescription = "P.......", UnitPrice = 15m},
}.ForEach(a => context.Products.AddOrUpdate(a));
context.SaveChanges();
这是我对 AssociatedProductsId 表的期望: ID + ProductId (FK) + AssociatedProductsId(FK) + 日期 + ......
但这就是我得到的:
我的错误是什么? 这是关联产品的好方法吗?
【问题讨论】:
标签: c# .net entity-framework ef-code-first ef-fluent-api