开发者

ASP.NET MVC: Repository pattern high concurrency updates

开发者 https://www.devze.com 2023-02-01 02:25 出处:网络
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'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 pro开发者_如何学编程perties 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?


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 you're 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消