的EntityFramework。删除所有行,然后添加新行。异步

时间:2015-06-25 09:26:49

标签: c# asp.net sql-server entity-framework asynchronous

我正在通过ASP.NET MVC应用程序将CSV导入到SQL数据库中。

我正在迭代CSV中的所有行,为每个行创建一个等效实体,并将每个行添加到当前上下文中。

如果要添加至少一行,那么我想从正在写入的表中删除所有现有行,然后提交新实体。

我的问题是,在我调用ExecuteSqlCommandAsync之前调用await db.SaveChangesAsync();并且不等待结果是否安全:

db.Database.ExecuteSqlCommandAsync("delete from tblName");
await db.SaveChangesAsync();

或者,在我进行保存更改调用之前,我应该await删除调用吗?在这种情况下,我也可以调用非异步版本?

我目前没有等待它,一切似乎都在预期的本地工作(几乎没有延迟),即现有数据被删除,新数据被添加。我担心的是,在部署解决方案时,我是否应该考虑其他问题,而且Web服务器和SQL服务器不一定在同一个盒子上。

2 个答案:

答案 0 :(得分:1)

As per MSDN:

By default, a DELETE statement always acquires an exclusive (X) lock on the table it modifies, and holds that lock until the transaction completes.

This means that the save action will wait until the delete action has finished, even though the latter is started async. So, since you await the save call, in fact you also await the delete call.

I think I'd prefer to await the delete call explicitly (or don't call it async) because you might want to respond to any errors it raises (like not executing the save action but writing a log instead).

Side note: consider using TRUNCATE TABLE.

答案 1 :(得分:1)

EF不支持同时使用相同的对象。这不安全。现在有多个线程在这里写入相同的EF对象,除非另有说明,否则不安全。

即使这对EF来说是安全的,也不能保证在保存开始时删除甚至已经开始。

也缺少错误处理。

我不明白你为什么要这样做。这会带来什么好处?当然没有更多的吞吐量。延迟也不会减少,因为删除必须在保存开始之前完成。