Linq to sql add/update in different methods with different datacontexts

后端 未结 4 1563

I have to methods, Add() and Update() which both create a datacontext and returns the object created/updated.

In my unit test I call first Add(), do some stuff and

4条回答
  •  感情败类
    2021-01-07 07:24

    It's only OK if you don't reuse the object. Once an entity instance object is associated with a data context, information about that data context is added for change tracking purposes. If you try to reuse that object in a different data context, you get the error you got.

    If you're working with different data contexts, it is advisable to create a new entity object and perform the add within that first data context, then retrieve that record using the other data context and do the updates with the new entity object.

    The reasoning is that there is no way to guarantee that the information won't change between operations if you only use a single entity object and multiple data contexts. Each data context tracks and manages the changes based on the state of the database object at the time the entity object was created.

提交回复
热议问题