ASP.NET MVC: Repository pattern high concurrency updates

吃可爱长大的小学妹 提交于 2019-12-13 05:48:00

问题


I'm writing an app that we may be switching out the repository later (currently entity framework) to use either amazon or windows azure storage.

I have a service method that disables a user by the ID, all it does is set a property to true and set the DisabledDate. Should I call to the repository, get that user, set the properties in the service, then call to the save function in the repository? If I do this, then thats 2 database calls, should I worry about this? What if the user is updating the profile at the same time the admin is calling the disable method, and calls the user calls the save method in the repository (which currently holds false for the IsDisabled property?) Wouldn't that set the user back to being enabled if called right after the disabled method?

What is the best way to solve this problem? How do I update data in a high concurrent system?


回答1:


CustomerRepository:

// Would be called from more specific method in Service Layer - e.g DisableUser
public void Update(Customer c)
{
   var stub = new Customer { Id = c.Id }; // create "stub"
   ctx.Customers.Attach(stub); // attach "stub" to graph
   ctx.ApplyCurrentValues("Customers", c); // override scalar values of "stub"
   ctx.SaveChanges(); // save changes - 1 call to DB. leave this out if your using UoW 
}

That should serve as a general-purpose "UPDATE" method in your repository. Should only be used when the entity exists.

That is just an example - in reality you should/could be using generics, checking for the existence of the entity in the graph before attaching, etc.

But that will get you on the right track.




回答2:


As long as you know the id of the entity you want to save you should be able to do it by attaching the entity to the context first like so:

var c = new Customer();
c.Id = someId;
context.AttachTo("Customer", c)
c.PropertyToChange = "propertyValue";
context.SaveChanges();

Whether this approach is recommended or not, I'm not so sure as I'm not overly familiar with EF, but this will allow you to issue the update command without having to first load the entity.



来源:https://stackoverflow.com/questions/4515953/asp-net-mvc-repository-pattern-high-concurrency-updates

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