【发布时间】:2012-01-18 08:30:43
【问题描述】:
我们正在研究 EF 代码,以评估它是否适合我们现有的数据库。数据库实体的结构是
1) 产品(复合键)
int 产品 ID:PK(非身份)- 自动生成而不是触发器 int 版本来自:PK(非身份)- 自动生成而不是触发器
2) 包(复合键)
PackID : PK (Non Identity) - 自动生成而不是触发器 版本来自:PK(非身份)- 自动生成而不是触发器 产品 ID:(不能设置为 FK - 设计约束)
RelationShip:产品有很多包
我们如何使用 EF Code First 4.1 对上述场景进行建模?
尝试过的解决方案
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public short Version { get; set; }
public virtual ICollection<Pack> Packs { get; set; }
}
public class Pack
{
public int PackID { get; set; }
public int ProductID { get; set; }
public short Version { get; set; }
public virtual Product Product { get; set; }
}
public class ProductContext : DbContext
{
public DbSet<Pack> Pack { get; set; }
public DbSet<Product> Product { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().ToTable("Product");
modelBuilder.Entity<Pack>().ToTable("Pack");
modelBuilder.Entity<Product>()
.HasKey(a => new { a.ProductID, a.VersionFrom });
modelBuilder.Entity<Pack>()
.HasKey(a => new { a.PackID, a.VersionFrom });
modelBuilder.Entity<Product>().HasMany<Pack>(x => x.Packs).WithRequired().HasForeignKey(p => p.ProductID);
base.OnModelCreating(modelBuilder);
}
}
....
var product = new Product { ProductName = "EntTest1"};
var pack = new Pack {};
using (var productContext = new ProductContext())
{
product.Packs.Add(pack);
productContext.Product.Add(product);
productContext.SaveChanges(); //**ERROR**
}
....
在模型生成过程中检测到一个或多个验证错误:
System.Data.Edm.EdmAssociationConstraint: : Number of Properties in the Dependent and Principal Role in a relationship constraint must be exactly identical.
请帮忙!!!
【问题讨论】:
标签: entity-framework-4.1 ef-code-first one-to-many