문제

The architecture for my application is structured as follows:

UI (client-side)

User Interface (XAML)

VM (client-side)

The layer for all view models. This layer works with the DTOs from the service layer.

Service (server-side)

Communication interface for the client. The client consumes DTOs from this service layer. This layer does the transformation from DTOs to EF-Entities (and back). I do the transformation with the automapper.

Domain (server-side)

The whole businesslogic seperated in several domains. This layer works with the entities from the entity framework.

Data Acccess (server-side):

The data access layer works with the EF. This layer ist designed with the repository / unitofwork pattern.

My problem: The creation of a new record works well. But if I want to update a record, the EF doesn't know about the update. It always wants to create a new record. I assume, that the problem is, that the EF works with the references for the whole change-tracking mechanism. The automapper will always create a new record. Is this correct?

Are there any alternatives?

Thanks in advance.

Kind regards, pro

Edit: Summarization of my problem:

EF does not update in my n-layered architecture, it always wants to create a new record.

I hope that will help.

도움이 되었습니까?

해결책

You need to make a decision in your business layer based on characteristics of the entity. If your entity has an ID, then it must be already existing, and therefore you should use

context.YourEntities.Attach(entity);
context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);

but if it hasn't, then it's new, and you can use

context.YourEntities.AddObject(entity);

then after both paths,

context.SaveChanges();

다른 팁

You need to attach the entity :

var existingPerson = ctx.Persons.SingleOrDefault(p => p.Name = "Joe Bloggs" };
ctx.Persons.Attach(existingPerson);

Have a look at this answer for full details : Entity Framework 4 - AddObject vs Attach

And here is MSDN reference : http://msdn.microsoft.com/en-us/library/bb896271.aspx

For context lifespan details, have a look at this answer : Questions about Entity Framework Context Lifetime

You need to attach the entity, then change the entity state to Modified

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top