how to remove several rows of data using DbContext and Linq to EF

entity-framework linq


Within a project I have a database table with the following columns

enter image description here

I would like to be able to delete from this table all rows which have a matching SharingAgencyId and ReceivingAgencyId values that I can pass in.

What I have tried so far:

 public static ICollection<SecurityDataShare> UpdateSharedEntites(long conAgency, long recAgency)
            ICollection<SecurityDataShare> agShares = null;
                using (var context = new ProjSecurityEntities(string.Empty))
                    agShares = (from a in context.SecurityDataShares
                               .Where(c => c.ReceivingAgencyId == recAgency && c.SharingAgencyId == conAgency)
                                select a); 
            catch (Exception ex)

My thought process was to retrieve the records where the id's matched the parameters passed in and then using a foreach loop iterate through (agShare) and remove each row followed by saving my changes. With the current implementation I don't seem to have access to any of the Delete methods.

Looking to the example above I'd appreciate any suggestions on how to remove the rows within the table that contained a value of 43 and 39 using dbContext.


4/18/2012 4:53:54 PM

Accepted Answer

If I understand right, your DbContext's properties, like SecurityDataShares should be typed as IDbSet<SecurityDataShare>. If that's correct, you should be able to use this Remove method.

foreach(var agShare in agShares) {

Be aware that this creates a separate SQL statement for deleting these objects. If you expect the number of objects to be rather large, you may want to use a stored procedure instead.

4/18/2012 9:00:26 PM

Popular Answer

Entity Framework doesn't make it easy to run a single command to delete multiple rows (that I know of). My preference is to run a SQL statement directly for multi-entity updates/deletes using native sql with the dbcontext of sorts.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow