EF / Automapper and n-layered architecture
-
23-06-2021 - |
Domanda
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.
Soluzione
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();
Altri suggerimenti
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