[英]How to deal with concurrency on EF Core
I have a method that searches for an entity on database and attempts to create it if it doesn't exist. 我有一种方法可以搜索数据库中的实体,如果不存在则尝试创建它。 As an example: 举个例子:
public async Country FindOrCreate(string name)
{
var country = _context.Countries.FirstOrDefault(p => p.Name == name);
if (country != null)
return country;
country = new Country
{
Name = name
};
_context.Countries.Add(country);
_context.SaveChanges();
return country;
}
The problem is: there are several tasks in background calling FindOrCreate
concurrently. 问题是:后台有多个任务同时调用FindOrCreate
。 I have prevented duplicates from being inserted by creating an unique index, but the following happens, causing unwanted exceptions: 我已通过创建唯一索引来防止插入重复项,但是会发生以下情况,从而导致意外的异常:
What would be the appropriate way of handling these scenarios of concurrency? 处理这些并发方案的合适方法是什么? Should I work with locks using C# code? 我应该使用C#代码处理锁吗? Or should I set a transaction? 还是应该进行交易? TIA TIA
Handling concurrency at the DB level using unique index is the right approach here. 在这里,使用唯一索引在数据库级别处理并发是正确的方法。 Unique index will guarantee uniqueness of countries no matter what. 唯一索引无论如何都将保证国家的唯一性。
Don't bother locking the C# code, it will not work as soon as you've got more than 1 server running your app (these days it is likely). 不要费心锁定C#代码,一旦您有多台服务器运行您的应用程序(这可能是几天),它就不会起作用。 Transactions in this case are tricky business so I wouldn't bother. 在这种情况下,交易是一件棘手的事情,所以我不会打扰。
How to handle those exceptions: 如何处理这些异常:
In case your task failed when creating country, catch the exception and retry. 如果创建国家/地区时任务失败,请捕获异常并重试。 If you failed to get the country second time for some reason, log the exception and fail. 如果由于某种原因第二次无法获得该国家/地区,请记录该异常并失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.