dg777
dg777

Reputation: 17

Linq query delete record from child table

I using code first ASP.NET C#. Trying to delete records from the child table in one to many relationship where LoginBackEnds is parent table and AccessProviders child table.

LoginBackEnds table has the following fields: UserId, UserLastName, UserFirstName,

AccessProviders table has the following fields: AccessId, ProviderId, LoginBackEnd_UserId (Foreign Key of UserId in LoginBackEnds table)

Any suggestion for delete statement using linq query?

Thank you.

Upvotes: 0

Views: 1801

Answers (1)

Sam Leach
Sam Leach

Reputation: 12956

You need to get the Entities to remove if you have not already got them:

// Get the AccessProviders to delete
IQueryable<AccessProviders> accessProviders = context.LoginBackEnds.SingleOrDefault(x => x.UserId == userId).AccessProviders;

// Delete AccessProviders
foreach(AccessProvider accessProvider in accessProviders)
{
    context.AccessProviders.DeleteObject(accessProvider);
}
context.SaveChanges();

If you want to know the difference between DeleteObject() and Remove(), see my so question.

Upvotes: 1

Related Questions