[英]How to optimise inserting multiple records (with exists check) via Entity Framework
[英]Inserting Related Records into Database via Entity Framework
我很好奇是否有干凈的方法來做到這一點
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創建一個交易,如果有任何失敗,你將不會插入沒有產品圖像的幻影產品記錄 - 如果這是有道理的?
改變你的產品型號?
private IList<ProductImage> productImages_;
public virtual IList<ProductImage> ProductImages {
get {
return productImages_ ?? (productImages_= new List<ProductImage>());
}
set { productImages_ = value;}
}
我只是在這里進行頭腦風暴,所以如果這不起作用,請不要生氣,但我認為您可能需要在將其鏈接到Product實體之前將新的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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.