EntityState.Detached, do I need to reload?

All,

Using .Net 4 and EF 4.4 Database First.

Let's say I have a DbContext. I load data from this DbContext, do stuff, and then detach everything from the DbContext and dispose of the DbContext.

Then, I create a new DbContext (same model) and load other data that overlaps with data from the first DbContext. Do I need to, prior to executing my query, do Entry().Reload() or will the Detatched Entities refresh automatically when they're loaded into the new context.

The reason I ask is because I ran into an issue in the past with, when using the same DbContext, I had to manually reattach entities that were in a detached state and call Reload. So I'm wondering if in this situation the entities that were in a detached state from the prior DbContext are simply attached to the new DbContext or if they're also refreshed?

Yes, I know I could setup a simple test, but was curious to know if someone else out there has already done this so that they could share their findings with the SO Universe and save others wondering about this some time.

Hopefully this question makes sense.

Thanks.


Entities are not automatically attached to the new context. You must attach them manually. If you then just load overlapping data your entities will not be updated. You must force such update either by calling Reload or by using ObjectContext and MergeOption for the query. If you don't attach your detached entities and you just run the query on the new context you will get new data but you will have two instances of overlapped entities - one detached with old data and one attached with new data.


will the Detatched Entities refresh automatically when they're loaded into the new context?

No, they won't. Which is good, because you can attach changed entities (which often happens in a disconnected n-tier application). An automatic refresh would erase the changes. So you'll have to reload manually if you want a refresh.

链接地址: http://www.djcxy.com/p/33566.html

上一篇: 分离还是不分离? 实体框架IBindingList问题

下一篇: EntityState.Detached,我需要重新加载吗?