developer tip

엔티티 프레임 워크를 사용하여 ID로 객체를 삭제하는 방법

copycodes 2020. 9. 9. 08:11
반응형

엔티티 프레임 워크를 사용하여 ID로 객체를 삭제하는 방법


아래와 같이 엔티티 프레임 워크로 삭제하기 전에 객체를 검색해야하는 것 같습니다.

var customer = context.Customers.First(c => c.Id == 1);

context.DeleteObject(customer);

context.Savechanges();

그래서 저는 데이터베이스를 두 번 쳐야합니다. 더 쉬운 방법이 있습니까?


Entity Framework 6에서 삭제 작업은 Remove. 다음은 예입니다.

Customer customer = new Customer () { Id = id };
context.Customers.Attach(customer);
context.Customers.Remove(customer);
context.SaveChanges();

강력하게 입력해야하는 작은 변경 사항이있는 @Nix와 동일합니다.

쿼리하지 않으려면 엔터티를 만든 다음 삭제하면됩니다.

                Customer customer = new Customer () { Id = id };
                context.Customers.Attach(customer);
                context.Customers.DeleteObject(customer);
                context.SaveChanges();

여기에 비슷한 질문이 있습니다 .

Entity Framework에는 EntityFramework-Plus (확장 라이브러리)가 있습니다.
NuGet에서 사용할 수 있습니다. 그런 다음 다음과 같이 작성할 수 있습니다.

// DELETE all users which has been inactive for 2 years
ctx.Users.Where(x => x.LastLoginDate < DateTime.Now.AddYears(-2))
     .Delete();

대량 삭제에도 유용합니다.


쿼리하지 않으려면 항목을 만든 다음 삭제하면됩니다.

Customer customer  = new Customer() {  Id = 1   } ; 
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();

내 프로젝트 중 하나에서 다음 코드를 사용하고 있습니다.

    using (var _context = new DBContext(new DbContextOptions<DBContext>()))
    {
        try
        {
            _context.MyItems.Remove(new MyItem() { MyItemId = id });
            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            if (!_context.MyItems.Any(i => i.MyItemId == id))
            {
                return NotFound();
            }
            else
            {
                throw ex;
            }
        }
    }

This way, it will query the database twice only if an exception occurs when trying to remove the item with the specified ID. Then if the item is not found, it returns a meaningful message; otherwise, it just throws the exception back (you can handle this in a way more fit to your case using different catch blocks for different exception types, add more custom checks using if blocks etc.).

[I am using this code in a MVC .Net Core/.Net Core project with Entity Framework Core.]


Raw sql query is fastest way I suppose

public void DeleteCustomer(int id)
{
   using (var context = new Context())
   {
      const string query = "DELETE FROM [dbo].[Customers] WHERE [id]={0}";
      var rows = context.Database.ExecuteSqlCommand(query,id);
      // rows >= 1 - count of deleted rows,
      // rows = 0 - nothing to delete.
   }
}

dwkd's answer mostly worked for me in Entity Framework core, except when I saw this exception:

InvalidOperationException: The instance of entity type 'Customer' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

To avoid the exception, I updated the code:

Customer customer = context.Customers.Local.First(c => c.Id == id);
if (customer == null) {
    customer = new Customer () { Id = id };
    context.Customers.Attach(customer);
}
context.Customers.Remove(customer);
context.SaveChanges();

참고URL : https://stackoverflow.com/questions/2471433/how-to-delete-an-object-by-id-with-entity-framework

반응형