Insert related records into a database through the Entity Framework

I'm curious if there is a clean way to do this

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(); 

The problem I am facing is that product.ProductImages is null - I would like to make it so that INSTEAD executes multiple db.TableName.Add / db.SaveChanges, because if I understand it correctly EF creates a transaction, so if something doesn’t work out, you won’t have phantom product records inserted without product images - if that makes sense?

+4
source share
2 answers

change your product model?

 private IList<ProductImage> productImages_; public virtual IList<ProductImage> ProductImages { get { return productImages_ ?? (productImages_= new List<ProductImage>()); } set { productImages_ = value;} } 
+4
source

I'm just brainstorming here, so don't be discouraged if this doesn't work, but I think you might need to explicitly add a new ProductImage object to the db.ProductImages object before you associate it with the product object.

 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 
0
source

Source: https://habr.com/ru/post/1438018/


All Articles