How to delete an object by id with entity framework

后端 未结 9 1877
你的背包
你的背包 2020-11-29 04:05

It seems to me that I have to retrieve an object before I delete it with entity framework like below

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


        
9条回答
  •  一整个雨季
    2020-11-29 04:50

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

提交回复
热议问题