简体   繁体   中英

Updating EF6 code first entities from REST service

I'm using EF6 code first and I have a service layer where AutoMapper maps a DTO to an Entity type (this is an update so the object with the same ID already exists in the database). I would like to have the changes persisted to the database. Is it possible to perform the update with this completely new object which EF has no knowledge of or do I have to copy the property values over to the object which EF holds a reference to? What is the best practice for doing this? And what about the navigation properties? Do these have to be done the same way?

If you want to specifically mark an object as updated and not added (which is what EF would do by default if you just added it to the context), you can do that - context.Entry(entity).State = EntityState.Modified. You'd need to do it appropriately for associated entities as well and it can get a bit messy, but it would save you a query to the database to get the original entity.

I don't think there's one answer that fits all scenarios; one solution I worked on was to specify up-front the rules that would make entities be marked as updated or added (usually based on the autoincremented primary key being 0 or not). In another case with a highly relational model it was easier to query for the original object (including all the relationships inferred from the updated copy) and copy updated properties and relationships (again according to some rules).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM