我在创建数据库结构时遇到问题。例如,我有3个类
public class Product
{
[Key, Column(Order = 1)]
[Required]
public string ItemNo { get; set; }
[Key, Column(Order = 2)]
[Required]
public string VariantCode { get; set; }
public virtual List<ProductAttribute> Attributes { get; set; }
public Product()
{
Attributes = new List<ProductAttribute>();
}
}
public class ProductAttribute
{
[Key]
[Required]
public string FieldName { get; set; }
public string FieldValue { get; set; }
public virtual Product Item { get; set; }
}
public class DbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<ProductAttribute> Attributes { get; set; }
}
Product表的主键是ItemNo + VariantCode,将正确创建。第二个表ProductAttribute应该具有ItemNo + VariantCode + FieldName的键,但是上面的代码EF6创建一个主键FieldName和一个ItemNo + VariantCode的外键。我尝试了几个方法,包括将[Key]属性设置为ProductAttribute类中的Item属性,但这不起作用。任何想法如何做到这一点?
答案 0 :(得分:0)
请尝试以下操作:
public class ProductAttribute
{
[Key]
[Required]
public string FieldName { get; set; }
public string FieldValue { get; set; }
[Key]
[ForeignKey("Item"), Column(Order = 1)]
public string ItemNo { get; set; }
[Key]
[ForeignKey("Item"), Column(Order = 2)]
public string VariantCode { get; set; }
public virtual Product Item { get; set; }
}