PaulFrancis PaulFrancis - 1 year ago 62
C# Question

Delete many records per ID - MVC C#

The setup for the database I have is,

can have many
, and can be in many
. 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
, then I could use

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

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))
// 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