PaulFrancis PaulFrancis - 1 year ago 50
C# Question

Delete many records per ID - MVC C#

The setup for the database I have is,

Company
can have many
Engineer
, and can be in many
Territory
. If I am supposed to remove a company form the list, I need to make a clean exit, so instead of deleting just the Company form the company table. I have to make sure all records are deleted everywhere. So no child/related records become orphan data.

If I am to remove just one record from all the tables, I would simply delete it using
FirstOrDefault
, then I could use

public void RemoveCompany(long companyId)
{
using (var db = new BoilerServicingDbContext())
{
var ec = db.Engineers.FirstOrDefault(x => x.CompanyId == companyId);
db.Engineers.Remove(ec);
var tc = db.CompanyTerritories.FirstOrDefault(x => x.CompanyId == companyId);
db.CompanyTerritories.Remove(tc);
var p = db.Companies.FirstOrDefault(x => x.Id == companyId);
db.Companies.Remove(p);
db.SaveChanges();
}
}


However, there are more than one Engineer per company and more than one Territory per company. Is there a simple method, as in general database sense.

DELETE * FROM Engineers WHERE companyId = 1;


At this moment I do not have Cascading delete setup, so other than that. Any other options.

Answer Source

Why not to use .Where() method to find all corresponding items in DB? Like this:

foreach(var ec in db.Engineers.Where(x => x.CompanyId == companyId))
{
    db.Engineers.Remove(ec);
}
// same logic here for other tables

Also consider the @workabyte answer as there is a way to implement cascade delete in your database.

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