Vit*_*ubs 2 .net c# entity-framework
我有一种方法可以在数据库中搜索实体并尝试创建它(如果不存在)。举个例子:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题是:后台有多个任务FindOrCreate同时调用。我已通过创建唯一索引来防止插入重复项,但发生了以下情况,导致出现不需要的异常:
处理这些并发场景的适当方法是什么?我应该使用 C# 代码来处理锁吗?或者我应该设置交易吗?TIA
| 归档时间: |
|
| 查看次数: |
1427 次 |
| 最近记录: |