我在我的Products类上创建一对多关系到ProductSpecification类时遇到问题,该类有两个主键ProductId,SpecificationId。产品类并不总是有一个ProductSpecification类没有人没有如何解决我的问题我得到一个错误与上限1.我是EF的新手,并先做代码,所以如果你知道该怎么做请请留下详细解释谢谢。
类:
public class ProductSpecification
{
[Key]
[Column(Order = 1)]
public long ProductId { get; set; }
[Key]
[Column(Order = 2)]
public long SpecificationId { get; set; }
[ForeignKey("ProductId")]
public virtual Product Product { get; set; }
[ForeignKey("SpecificationId")]
public virtual Specification Specification { get; set; }
}
public class Specification
{
[Key]
public long SpecificationId { get; set; }
[Required(ErrorMessage = "Please enter a product specification name.")]
[DataType(DataType.Text)]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a product specification value.")]
[DataType(DataType.Text)]
public string Value { get; set; }
[ForeignKey("SpecificationId")]
public virtual ICollection<ProductSpecification> ProductSpecs { get; set; }
}
的DataContext:
modelBuilder.Entity<ProductSpecification>().HasKey(x => new { x.ProductId, x.SpecificationId });
modelBuilder.Entity<Specification>().HasOptional(x => x.ProductSpecs)
.WithMany().HasForeignKey(x => x.SpecificationId);
答案 0 :(得分:0)
使您的ForeignKey可以为空:
公众长吗? SpecificationId {get;组; }公共虚拟规范?规范{get;组; }