Entity Framework 4.1: how to work with per call life time data context?

混江龙づ霸主 提交于 2019-11-28 14:21:23

The service is disconnected scenario so when your client passes backs modified records you just need to process them as modified. You don't need to load all records from database for that.

public void SaveClients(List<Client> modifiedClients)
{
    using (var context = new Context())
    {
        modifiedClients.ForEach(c => 
           {
               context.Entry(c).State = EntityState.Modified;
           });
        context.SaveChanges(); 
    }
}

If you are using per call service and every service operation needs context you can move your context instancing to service constructor because service instance will live only to server single service call = you don't need using for every call. If you do that don't forget to implement IDisposable on your service to dispose context.

Other question is about concurrency. If I control the concurrency with pesimistic concurrency that allow EF (with a timestamp field for example), is it better to call the updateClient() one for each client or better to pass a list with all the clients?

EF doesn't support pesimistic concurrency out of the box. Using timestamp is optimistic concurrency because it allows others to use the record. Pesimistic concurrency is application logic where other client is not able to select locked record for update.

The concurrency is resolved per record but the problem in this case is transaction. Each call to SaveChanges results in transaction used to process all changes in the database. So if any of your modified records is not up to date you will get concurrency exception and whole transaction is rolled back = no record is updated.

You can still overcome the issue by passing list of modified records to the service (reducing roundtrips between client and service is a best practice) but you can process each record separately by calling SaveChanges for every single record. Anyway this should be very carefully considered because each call to SaveChanges is like separate unit of work - is it really what you want?

Btw. the best practice is to make your service statless. You should avoid maintaining data between service calls and this example really doesn't need it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!