我有类似下面的课程。我想首先使用实体框架代码重用类并将它们保存在不同的表中。
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsAvailable { get; set; }
public List<Part> Parts { get; set; }
public List<Promotion> Promotions { get; set; }
}
public class Field
{
public int Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
public class Part
{
public int Id { get; set; }
public string Name { get; set; }
public List<Field> Details { get; set; }
}
public class Promotion
{
public int Id { get; set; }
public string Name { get; set; }
public List<Field> Details { get; set; }
}
我想以这样的方式映射我的实体,以便生成如下所示的数据库表。
产品:Id,Name,IsAvailable
ProductParts: Id,Name,ProductId
ProductPartDetails: Id,Name,Value,ProductPartId
ProductPromotions: ID,Name,ProductId
ProductPromotionDetails: ID,名称,价值,ProductPromotionId
我真正感兴趣的是我希望 Field 类重复使用并存储在不同的表 ProductPartDetails 和 ProductPromotionDetails 中,如我所述以上。是否有可能或我的方法需要改变?
答案 0 :(得分:1)
你可以 - 但你需要重新安排一切。
你应该制作多对手的'手册'(定义像ProductPartDetails等自定义类),
为它定义流畅的配置
e.g。 (更多伪代码)
[ComplexType()]
public class Field
{}
public class ProductPartDetails
{
public int ProductId { get; set; }
public int PartId { get; set; }
public virtual Product Product { get; set; }
public virtual Part Part { get; set; }
public Field Field { get; set; }
}
modelBuilder.Entity<ProductPartDetails>()
.HasKey(x => new { x.ProductId, x.PartId });
modelBuilder.Entity<ProductPartDetails>()
.HasRequired(i => i.Product)
.WithMany(u => u.Details)
.HasForeignKey(i => i.ProductId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ProductPartDetails>()
.HasRequired(i => i.Part)
.WithMany(u => u.Details)
.HasForeignKey(i => i.PartId)
.WillCascadeOnDelete(false);
让
Details
现在指向ProductPartDetails
,而不是。{Field
。
...并将Field
作为属性添加到该表中。
使字段ComplexType使其“重用”(仅转换为字段,而不是自己的表)。这两者都是这样的。
e.g。 EF code-first many-to-many with additional data
Code First Fluent API and Navigation Properties in a Join Table
ASP.Net MVC 3 EF "Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths"