我们首先研究EF代码,以评估它是否适合我们现有的数据库。数据库的结构是
1)产品(复合键)
int产品ID:PK(非身份) - 自动生成而不是触发器 int Version From:PK(非身份) - 自动生成而不是触发
2)打包(复合键)
PackID:PK(非身份) - 自动生成而不是触发器 版本来自:PK(非身份) - 自动生成而不是触发器 产品编号:(不能设置为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.
请帮助!!!
答案 0 :(得分:1)
您的Pack
类需要两个外键标量属性
public class Pack
{
public int PackID { get; set; }
public int ProductID { get; set; }
public short ProductVersion { get; set; }
public virtual Product Product { get; set; }
}
您需要为映射提供两个标量属性
modelBuilder.Entity<Product>()
.HasMany<Pack>(x => x.Packs).WithRequired(p => p.Product)
.HasForeignKey(p => new { p.ProductID, p.ProductVersion});
编辑:不映射标量属性
public class Pack
{
public int PackID { get; set; }
public virtual Product Product { get; set; }
}
modelBuilder.Entity<Product>()
.HasMany<Pack>(x => x.Packs).WithRequired(p => p.Product)
.Map(m => m.MapKey("ProductID", "ProductVersion"));
您的Pack(s)
表格应包含匹配数据类型的ProductID
,ProductVersion
列。