views:

21

answers:

2

I am using DTOs and converters in an entity framwork scenario. I want to update an entity. So I put this statement: databasecontext.Tablename(s).Attach(entityobj); Whenever it gets here the program ends with this error: An entity with the same identity already exists in this EntitySet.

I felt i could get around this by saying:databasecontext.Tablename(s).Detach(entityobj);

before i called Attach again. But the program still fails on the Attach statement.

What am i missing? Which method on the DB context calls Update in the Domain Service?

Thanks for the answers in advance.

A: 

It looks like you are keeping the context open while you make the changes.

In that case you do not need to reattach the object to the context.

If you open a context, get an object from a context, then close the context, make some changes to the object, then open a new context. In this case you need to attach the object to the context.

Shiraz Bhaiji
A: 

The question is not clear. You didn't mentioned how long does your database context live and when did you load entity into context.

But based on your question I guess that you have loaded entity passed it somewhere as DTO and when the DTO is returned you are using still the same context. You convert DTO to entity and you are trying it to attach again => BANG exception. The same entity cannot be placed twice into context. Try to use ObjectContext.ApplyCurrentValues instead (EF 4.0) or ApplyPropertyChanges (EF 1.0).

Ladislav Mrnka