I have a "Create New Employee" ASP.Net MVC form.
My complex object is an Employee and an Employee has an Address, which is another Complex object.
On my View/Form I collect all required values for both the Employee and the Address.
I'm using the bound HTML helpers such as:
Html.TextBoxFor(model => model.EmployeeAddress.StreetName)
AND
Html.TextBoxFor(model => model.NewEmployee.FirstName)
etc
This is all working beautifully well. Model binding is working like a dream, both server side and client side validation using DataAnnotations is working beautifully well and I am nicely receiving my populated complex objects as expected in the Controller..
Now I'm trying to save..
So I wrote a nifty GetExistingOrCreateNewAddress(Address PostedAddress) method which works great so I end up with the correct Address to use and link to the about to be saved Employee object. This is all happening in the same DataContext, so no problems there..
BUT even when I link the about to be saved Employee object to an existing Address, on save a new/empty Address row is created in my Addresses table. Even though the newly created Employee does link correctly to the existing Address I told it to!
Why is it so??? And how can I save the new Employee without LINQ automatically creating a blank Address for me. Because I'm explicitly specifying an existing Address it should be linked to instead!
This is what my controller looks like:
[HttpPost]
public ActionResult CreateEmployee(EmployeeDetailsViewModel NewEmployeeDetails)
{
if (ModelState.IsValid)
{
EmployeeRepository ER = new EmployeeeRepository();
// Fetch or Create the appropriate Address object for what has been entered
Address ActualAddress = ER.GetExistingOrCreateNewAddress(NewEmployeeDetails.EnteredAddress);
// Link this Address to the "about to be saved" Employee
NewEmployeeDetails.Employee.Address = ActualAddress;
// Lock it in..
ER.SaveNewEmployee(NewEmployeeDetails.Employee);
I'm not getting any errors whatsoever!
Can anyone explain??
I figured it out.
Inside my Address complex object, it also has a further child complex object called "Suburb". I was going to the database within the same DataContext and fetching the appropriate Suburb object to attach to my Address object.
This was all being done inside a custom method inside my Data Repository class.
Even after later nulling that same Address out and assigning its value to SomeExistingAddress, LINQ or model binding still felt that it needed to create a blank Address. This was because I had previously linked the above chosen Suburb record (attached to the database, wasn't using ToList()) to a detached/local Address object. As a result, whether I liked it or not, LINQ felt that it needed to now create a blank new (but with Primary Key) Address object because the linked Suburb had to belong to something, which was previously detached. I hope that makes sense. So my solution was that when fetching the Suburb out to populate in the Address which in turn was to populate the Employee, I had to make sure I fetched the Suburb with ToList() before doing that query to find the right one. Without ToList() it created some expectation that I needed the parent entity freshly re-created even after nulling it out.
Really weird and I don't understand it fully yet, but kind of do. My lesson:
"When needing to populate child complex object values of a detached/local parent complex object, ensure you only attached other detached objects, never attach pre-attached ones. Because LINQ will forcibly create a blank copy of the complex parent object simply because it is detached from the database while its child object isn't, therefore it thinks it needs to Insert a new instance of the parent. Instead, just work locally/detached all the way, and SubmitChanges together at once.
This was the old broken code:
FauxAddress.Suburb = db.Suburbs.Where(x => x.SuburbName == FauxAddress.Suburb.SuburbName && x.Postcode == FauxAddress.Suburb.Postcode).FirstOrDefault();
This is the new/resolved code:
FauxAddress.Suburb = db.Suburbs.ToList().Where(x => x.SuburbName == FauxAddress.Suburb.SuburbName && x.Postcode == FauxAddress.Suburb.Postcode).FirstOrDefault();