如何使用ExecuteSqlCommand删除实体框架中的记录?

时间:2016-04-23 07:18:51

标签: c# entity-framework

这是我的代码:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, transactionOption))
{
    foreach (ManufacturecodeEntity mcodeEntity in ManufacturecodeEntities)
    {
         ManufacturecodeEntity pcodeEntity = mcodeEntity.Parent;
         pcodeEntity.IsCurrent = true;

         UnitOfWork.ManufacturecodeRepository.Update(pcodeEntity);
    }

    UnitOfWork.DbContext.Database.ExecuteSqlCommand("Delete from manufacturecodes where detailstate_id=" + Id.ToString());
    UnitOfWork.SaveChanges();

    scope.Complete();
}

但是当我运行方法ExecuteSqlCommand时,我的应用程序停止,然后抛出超时异常。

我使用ExecuteSqlCommand删除记录,因为记录超过1500,如果我使用实体框架DeleteSaveChanges方法,则需要60秒,我无法接受结果。

所以我尝试使用ExecuteSqlCommand方法来提高性能。现在看来有些不对劲。

请帮帮我,谢谢。

2 个答案:

答案 0 :(得分:1)

您应该使用SqlParameters中的ExecuteSqlCommand作为:

UnitOfWork.DbContext.Database.ExecuteSqlCommand("Delete from manufacturecodes where detailstate_id=@id", new SqlParameter("@id", id);

答案 1 :(得分:0)

我想我知道正确的方法。我应该使用DbContext.Database.BeginTransaction而不是TransactionScope