我很好奇是否有干净的方法来做到这一点
Product product = new Product();
product.CreateDateTime = DateTime.Now;
product.Description = productCreateModel.Product.Description;
product.ManufacturerId = productCreateModel.Manufacturer;
product.MetaDescription = productCreateModel.Product.MetaDescription;
product.MetaTitle = productCreateModel.Product.MetaTitle;
product.Name = productCreateModel.Product.Name;
product.Status = ProductStatuses.Active;
product.URL = productCreateModel.Product.URL;
if (productCreateModel.ProductImage1.ContentLength > 0)
{
BinaryReader binaryReader = new BinaryReader(productCreateModel.ProductImage1.InputStream);
product.ProductImages.Add(new ProductImage()
{
CreateDateTime = DateTime.Now,
Image = binaryReader.ReadBytes(productCreateModel.ProductImage1.ContentLength),
PrimaryImage = true
});
}
db.Products.Add(product);
db.SaveChanges();
我遇到的问题是product.ProductImages为null - 我希望能够这样做INSTEAD做多个db.TableName.Add / db.SaveChanges,因为如果我理解正确的话EF创建一个交易,这样如果有任何失败,你就不会插入没有产品图片的幻影产品记录 - 如果这样做有意义的话?
答案 0 :(得分:4)
更改您的产品型号?
private IList<ProductImage> productImages_;
public virtual IList<ProductImage> ProductImages {
get {
return productImages_ ?? (productImages_= new List<ProductImage>());
}
set { productImages_ = value;}
}
答案 1 :(得分:0)
我只是在这里进行头脑风暴,所以如果这不起作用,请不要生气,但我认为您可能需要在将其链接到产品之前将新的ProductImage实体显式添加到db.ProductImages实体集中实体。
Product product = new Product();
product.CreateDateTime = DateTime.Now;
product.Description = productCreateModel.Product.Description;
product.ManufacturerId = productCreateModel.Manufacturer;
product.MetaDescription = productCreateModel.Product.MetaDescription;
product.MetaTitle = productCreateModel.Product.MetaTitle;
product.Name = productCreateModel.Product.Name;
product.Status = ProductStatuses.Active;
product.URL = productCreateModel.Product.URL;
db.Products.Add(product);
if (productCreateModel.ProductImage1.ContentLength > 0)
{
BinaryReader binaryReader = new BinaryReader(productCreateModel.ProductImage1.InputStream);
ProductImage image = new ProductImage()
{
CreateDateTime = DateTime.Now,
Image = binaryReader.ReadBytes(productCreateModel.ProductImage1.ContentLength),
PrimaryImage = true
}
db.ProductImages.Add(image); // Add the image to the ProductImage entity set
product.ProductImages.Add(image); // link the image to this Product
}
db.SaveChanges(); // Save all changes