Ashkan Mobayen Khiabani Ashkan Mobayen Khiabani - 1 year ago 63
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);

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 Source

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download