简体   繁体   中英

How to update entity in Entity-Framework?

I have built an ASP.NET MVC web application that uses Entity Framework. To provide the view with correct data I have created special view classes that represent parts of the model classes.

I have 2 questions about this.

  1. How do I best convert data from the view object to the model object? For now I am doing this manually in methods like ViewClass.ToModel() and ViewClass.FromModel(ModelClass). However if the model is updated then this conversion may have to be updated. Do I really have to do this manually?

  2. When converting a viewobject to a modelobject it can happen that some of the properties is not set so the value will be null or string.empty. The problem with this is that when running refresh(in entityframework) this empty(not set) properties will be overwriting the real data. How should I handle this?

One solution may be to get the modelobject from database and then only transfare the peroperties that have been set to the modelobject? Problem with this might be that a value on a property could be set to null, how do I know if this propertie is set or not? Or do I have to write special update methods depending on the action?

BestRegards

How do I best convert data from the view object to the model object?

AutoMapper

When converting a viewobject to a modelobject it can happen that some of the properties is not set so the value will be null or string.empty. The problem with this is that when running refresh(in entityframework) this empty(not set) properties will be overwriting the real data. How should I handle this?

If your data access layer (no matter what technology it is using, Entity Framework, NHibernate, ...) is not capable of handling this scenario you might need to have specially tailored update methods that work for those cases.

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