-1

我有这张桌子和班级:

   public abstract class ProductBase
{
    public int Id { get; set; }
} 
public class Product:ProductBase
{

    public virtual ICollection<ProductType> Types { get; set; } = new HashSet<ProductType>();
    public virtual ICollection<OnlineStock> OnlineStocks { get; set; } = new HashSet<OnlineStock>();
}
public abstract class ProductTypeBase
{
    [Key]
    public int Id { get; set; }
    public int ProductId { get; set; }
    public int Quantity{ get; set; }
    [ForeignKey("ProductId")]
    protected virtual Product Product { get; set; }
}
public class ProductType:ProductTypeBase
{
    public new Product Product
    {
        get { return base.Product; }
        set { base.Product = value; }
    }
}
public class OnlineStock:ProductTypeBase
{
    public new Product Product
    {
        get { return base.Product; }
        set { base.Product = value; }
    }
    public virtual ICollection<ProductTypePicture> Pictures { get; set; } = new HashSet<ProductTypePicture>();

}

当我想使用 producttype 添加新产品时。

Context.Porduct.Add(new Product
    {
     Types=new List<ProductTypes>
          {
             new ProductTypes {Quantity=8}
          }
    })

ef 错误:“无法将 'ProductType' 类型的对象转换为 'OnlineStock' 类型。”

我也有这个配置:

entityBuilder.Entity<Product>().HasMany(x=>x.Types).WithOne(x=>x.Product).HasForeignKey("ProductId");
        entityBuilder.Entity<Product>().HasMany(x=>x.OnlineStocks).WithOne(x=>x.Product).HasForeignKey("ProductId");
4

1 回答 1

0

我临时解决了这个问题。

    var NP=new Product(); 
    Context.Porduct.Add(NP);
    Context.saveChanges();
    NP.Types.Add(new ProductTypes
              {
                  Quantity=8
              });
   Context.saveChanges();
于 2017-08-10T10:58:10.900 回答