user2155362
user2155362

Reputation: 1713

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.

Upvotes: 2

Views: 1620

Answers (2)

user2155362
user2155362

Reputation: 1713

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

Upvotes: 0

M.S.
M.S.

Reputation: 4443

You should use SqlParameters in the ExecuteSqlCommand as:

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

Upvotes: 2

Related Questions