Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 3 months ago 12
C# Question

Linq to Entities Remove without fetching

Can this code:

using(DbContext db = new DbContext())
{
IEnumerable<Setting> settings = db.Settings.Where(s=> s.UserId==Uid);
db.Settings.RemoveRange(settings);
}


Be written in some way that there would be no need for fetching first? something like:

using(DbContext db = new DbContext())
{
db.Settings.Remove(s=> s.UserId==Uid);
}

Answer

You can have a look at the EntityFramework.Extended Library which offers you to write the below query:

//delete all Settings where UserId matches
db.Settings.Where(s=> s.UserId == Uid).Delete();

Docs:

A current limitations of the Entity Framework is that in order to update or delete an entity you have to first retrieve it into memory. Now in most scenarios this is just fine. There are however some scenarios where performance would suffer. Also, for single deletes, the object must be retrieved before it can be deleted requiring two calls to the database. Batch update and delete eliminates the need to retrieve and load an entity before modifying it.

Comments