Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting rows in a table with Linq to SQL

Tags:

c#

sql

asp.net

linq

I have a sports database with a table groupmembers which have the fields ID, groupID and memberID. I get the memberID from a textbox called txtRemoveGroupMember and the groupID from a checkboxlist. Now I want to delete the rows which have both the groupID and the memberID. I have tried this code:

foreach(ListItem listItem in cblRemoveMemberFromGroup.Items)
{
       int memberid = Convert.ToInt32(txtRemoveGroupMember.Text);
       int groupid = Convert.ToInt32(listItem.Value);

       var removeFromGroup = from gm in dataContext.GroupMembers
            where (gm.memberID == memberid) && (gm.groupID == groupid)
            select gm;

       dataContext.GroupMembers.DeleteOnSubmit(removeFromGroup);
       dataContext.SubmitChanges();
}

But I get this error:

Error 7 Argument 1: cannot convert from 'System.Linq.IQueryable<GSI_side.GroupMember>' to 'GSI_side.GroupMember'

And this error:

Error 6 The best overloaded method match for 'System.Data.Linq.Table<GSI_side.GroupMember>.DeleteOnSubmit(GSI_side.GroupMember)' has some invalid arguments

Hope someone can help me figure this out!

like image 390
Twistar Avatar asked Feb 29 '12 16:02

Twistar


People also ask

How do I delete multiple records in LINQ?

You can drag the SPROC to your DBML file and it will generate a rich method in your databasecontext class. Show activity on this post. First, you can find a list of the items you want to delete.

How we can truncate a table using LINQ?

context. ExecuteCommand("TRUNCATE TABLE Entity"); The way you are deleting is taking long because Linq to SQL generates a DELETE statement for each entity, there are other type-safe approaches to do batch deletes/updates, check the following articles: Batch Updates and Deletes with LINQ to SQL.


1 Answers

removeFromGroup is still of type IQuerable.

You need to specify an actual GroupMember to delete.

You could use

GroupMember removeFromGroup = (from gm in dataContext.GroupMembers
                               where (gm.memberID == memberid) && (gm.groupID == groupid)
                               select gm).SingleOrDefault();


dataContext.GroupMembers.DeleteOnSubmit(removeFromGroup);
dataContext.SubmitChanges();

Alternatively, if your query returns a collection (from the looks of it, it won't since you are filtering by memberId) you could use

List<GroupMember> removeFromGroup = (from gm in dataContext.GroupMembers
                                     where (gm.memberID == memberid) && (gm.groupID == groupid)
                                     select gm).ToList();


dataContext.GroupMembers.DeleteAllOnSubmit(removeFromGroup);
dataContext.SubmitChanges();
like image 64
Jeremy Wiggins Avatar answered Sep 19 '22 05:09

Jeremy Wiggins