[英]ASP.NET Core Web API and Entity Framework simultaneously check if entity exists in database
I'm developing an ASP.NET Core Web API project using Entity Framework.我正在使用 Entity Framework 开发一个 ASP.NET Core Web API 项目。 API requests are constantly coming from a source and I receive them, I check with linq whether the account number field has been added to the database before, if not, I add it, but sometimes 20 requests can come from the API source at the same time and duplicate records may occur.
API请求不断来自一个来源,我收到它们,我用linq检查之前是否已将帐号字段添加到数据库中,如果没有,我添加它,但有时20个请求可以同时来自API源时间和重复记录可能会发生。
How can I prevent this situation?我怎样才能防止这种情况?
var account = dbContext.Accounts
.FirstOrDefault(x => x.AccountNumber == apiMessage.AccountNumber);
if (account is null)
{
account = new Account();
account.AccountNumber = apiMessage.AccountNumber;
}
Just handle it in database side to make it easy.只需在数据库端处理它就可以了。 Add Unique constraint in the AccountNumber column.
在 AccountNumber 列中添加唯一约束。
You can handle the migration in your EF configuration您可以在 EF 配置中处理迁移
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Account>()
.HasIndex(u => u.AccountNumber)
.IsUnique();
}
You can wait for the controller to finish before starting a new one (No concurrent calls), but that will not be a good solution.您可以等待控制器完成后再开始新的控制器(无并发调用),但这不是一个好的解决方案。
If you do that, the requests will either wait for their turn, which decreases performance.如果您这样做,请求将等待轮到它们,这会降低性能。
Or they will not run at all if the controller is already working, which will result in a controller not answering all the requests.或者,如果控制器已经在工作,它们根本不会运行,这将导致控制器无法响应所有请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.