简体   繁体   English

ASP.NET MVC:存储库模式高并发更新

[英]ASP.NET MVC: Repository pattern high concurrency updates

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.我正在编写一个应用程序,稍后我们可能会切换存储库(当前为实体框架)以使用亚马逊或 Windows Azure 存储。

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.我有一个通过 ID 禁用用户的服务方法,它所做的只是将一个属性设置为 true 并设置 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?如果我这样做,那就是 2 个数据库调用,我应该为此担心吗? 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?如果用户在管理员调用禁用方法的同时更新配置文件,并调用用户调用存储库中的保存方法(当前 IsDisabled 属性为 false?),这不会让用户退缩吗?如果在禁用方法之后立即调用是否启用?

What is the best way to solve this problem?解决这个问题的最佳方法是什么? How do I update data in a high concurrent system?如何在高并发系统中更新数据?

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:只要您知道要保存的实体的 ID,就应该能够通过首先将实体附加到上下文来实现,如下所示:

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.我不太确定是否推荐这种方法,因为我对 EF 不太熟悉,但这将允许您发出更新命令而无需先加载实体。

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.这应该作为您存储库中的通用“UPDATE”方法。 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.但这会让你走上正轨。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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