Why should I use GetOriginalEntityState() in my LINQ To SQL repository save method?

£可爱£侵袭症+ 提交于 2019-12-04 07:01:59

This is a little bit of a guess since I have never actually used GetOriginalEntityState but the question peaked my interest to figure out what is going on.

I think the intent here is to check that product is still attached to the original DataContext

The line:

if (productsTable.GetOriginalEntityState(product) == null) 

I think this will return null if product has been dettached or created manually and not handled by the DataContext.

From MSDN:

This method returns the original state of an entity since it was either created or attached to the current DataContext. The original state of an entity that has been serialized and deserialized must be provided by an independent tracking mechanism and supplied when the entity is attached to a new DataContext. For more information, see Data Retrieval and CUD Operations in N-Tier Applications (LINQ to SQL).

I think the key line to understand is:

This method returns the original state of an entity since it was either created or attached to the current DataContext.

GetOriginalEntityState is used so that the method can receive an object with the option of not being attached already to the DataContext. Attached meaning, returned by a Linq To SQL call vs just creating an instance like Product p = new Product() { ... };. If it is not attached, it will attach it to the DataContext and keep any of the values that were modified (preserving the update values) due to the RefreshMode.KeepCurrentValues param.

Then the productsTable.Context.SubmitChanges(); always happens since even if it is dettached, the GetOriginalEntityState will make sure it gets attached so the submit will work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!