I’m looking at an example of a save method in a Products repository from Steven Sanderson’s book, Pro ASP.NET MVC 2 Framework:
public void SaveProduct(Product product)
{
// if new product, attach to DataContext:
if (product.ProductID == 0)
productsTable.InsertOnSubmit(product);
else if (productsTable.GetOriginalEntityState(product) == null)
{
// we're updating existing product
productsTable.Attach(product);
productsTable.Context.Refresh(RefreshMode.KeepCurrentValues, product);
}
productsTable.Context.SubmitChanges();
}
I do not understand the logic in the else if line:
else if (productsTable.GetOriginalEntityState(product) == null)
As I understand it, GetOriginalEntityState() returns the original state of the specified entity.. in this case that entity is product.
So this else if statement reads to me like: “If an original doesn’t exist then…” but that doesn’t make sense because the book is saying that this checks that we are modifying a record that already DOES exist.
How should I understand GetOriginalEntityState in this context?
Edit
By the way, this excerpt came from chapter 6, page 191… just in case anyone has the book and wants to look it up. The book just has that function in the code sample but it never explains what the function does.
This is a little bit of a guess since I have never actually used
GetOriginalEntityStatebut the question peaked my interest to figure out what is going on.I think the intent here is to check that
productis still attached to the originalDataContextThe line:
I think this will return null if
producthas been dettached or created manually and not handled by theDataContext.From MSDN:
I think the key line to understand is:
GetOriginalEntityStateis used so that the method can receive an object with the option of not being attached already to theDataContext. Attached meaning, returned by a Linq To SQL call vs just creating an instance likeProduct p = new Product() { ... };. If it is not attached, it will attach it to theDataContextand keep any of the values that were modified (preserving the update values) due to theRefreshMode.KeepCurrentValuesparam.Then the
productsTable.Context.SubmitChanges();always happens since even if it is dettached, theGetOriginalEntityStatewill make sure it gets attached so the submit will work.