Entity Framework Retain one-to-one relationships when splitting tables

For performance, I decided to split the table following this technique . So basically I have a second entity for storing a binary field. These are my classes:

public partial class CustomerDoc { public byte[] Document { get; set; } public int CustomerID { get; set; } public virtual Customer customer { get; set; } } public partial class Customer { public int CustomerID { get; set; } public string Name { get; set; } public virtual CustomerDoc CustomerDoc { get; set; } } 

Now, when I try to update the Document property in an existing client instance with a downloaded file, this value is not stored in the database, other properties are saved, but not Document.

  [HttpPost] public virtual ActionResult Edit(Customer customer, HttpPostedFileBase file) { if (ModelState.IsValid) { //code to modify other properties if (file != null && file.ContentLength > 0) { BinaryReader b = new BinaryReader(file.InputStream); byte[] binData = b.ReadBytes((int)file.InputStream.Length); customer.CustomerDoc= new CustomerDoc { CustomerID = customer.CustomerID, Document = binData }; } db.Entry(customer).State = EntityState.Modified; db.SaveChanges(); } 

I checked that other properties were changed correctly.

CustomerDoc is relevant after calling SaveChanges, but is not stored in the database.

I also tried updating the second instance of the same client inside the IF statement, but I get a bunch of errors

This is the detailed information:

 Mapping Details - CustomerDoc Maps to Customer Column Mapping CustomerID : int <-> *CustomerID : Int32 Document : varbinary(max) <-> Document: Binary 
+4
source share
2 answers

The solution is to keep the customerDoc object independent of the client.

 if (file != null && file.ContentLength > 0) { BinaryReader b = new BinaryReader(file.InputStream); byte[] binData = b.ReadBytes((int)file.InputStream.Length); var customerDoc = new CustomerDoc { CustomerID = customer.CustomerID, Document = binData }; db.Entry(customerDoc).State = EntityState.Modified; db.SaveChanges(); } 
0
source

Replace the internal if code in the code as follows:

 if (file != null && file.ContentLength > 0) { BinaryReader b = new BinaryReader(file.InputStream); byte[] binData = b.ReadBytes((int)file.InputStream.Length); var customerDoc = new CustomerDoc { CustomerID = customer.CustomerID, Document = binData }; db.Set<CustomerDoc>().Add(customerDoc); } 
0
source

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


All Articles