简体   繁体   中英

How can I delete records in Entity Framework using ExecuteSqlCommand?

This is my code:

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();
}

But when I run to method ExecuteSqlCommand , my application stops, then throws timeout exception.

I use ExecuteSqlCommand to delete records because records is more than 1500, if I use Entity Framework Delete and SaveChanges method, it will take 60s, I can't accept the result.

So I try the ExecuteSqlCommand method to improve the performance. Now it seems there is something wrong.

Please help me, thanks.

您应该在ExecuteSqlCommand使用SqlParameters作为:

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

I think I know correct way. I should use DbContext.Database.BeginTransaction instead of TransactionScope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM