在Entity Framework中處理并發通常有兩種方法:
public class MyEntity
{
public int Id { get; set; }
[ConcurrencyCheck]
public string ConcurrencyToken { get; set; }
}
using (var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted }))
{
using (var context = new MyDbContext())
{
var entity = context.MyEntities.FirstOrDefault(e => e.Id == entityId);
if (entity != null)
{
// 修改實體屬性
context.SaveChanges();
}
}
scope.Complete();
}
根據實際需求和業務場景選擇合適的并發控制方式來處理并發沖突。