[英]Create a key of 3 columns including a relation to another table (code first)
i have a problem creating my database structure. 我在创建数据库结构时遇到问题。 For example i have those 3 classes 例如我有那三个班
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; }
}
The primary key for the Product table is ItemNo + VariantCode and will be created correctly. 产品表的主键是ItemNo + VariantCode,并且可以正确创建。 The second table ProductAttribute should have a key of ItemNo + VariantCode + FieldName but with the code above EF6 creates a primary key FieldName and a foreign key of ItemNo + VariantCode. 第二个表ProductAttribute应该具有ItemNo + VariantCode + FieldName的键,但是使用EF6以上的代码创建主键FieldName和ItemNo + VariantCode的外键。 I have tried several things including setting the [Key] attribute to the Item property in the ProductAttribute class but this doesn't work. 我尝试了几件事,包括将[Key]属性设置为ProductAttribute类中的Item属性,但这不起作用。 Any ideas how to do this? 任何想法如何做到这一点?
Try following: 请尝试以下操作:
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; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.