0

Often times in our code we check for an entity being edited/deleted whether it has any related records and show the user a warning/error message: for example, Person "A" has following cars in the lot: car1, car2, car3 and cannot be deleted.

We find ourselves writing this sort of logic:

var cars = dbContext.AsNoTracking.Cars.Where(c => c.Person.Id == person.Id).Select(c => c.Name).ToList();

This happens for many entities with many different relationships. I'm just wondering since EF/DB already has a way of checking relationship info, if there's a generic way of checking this so we don't have to repeat this for every entity. I would like to just be able to pass an entity/class Type to a function which then evaluates all this and returns me a list of relationships and specific entities within each. I already now how to use reflection to check relationship info, but not sure know to then fetch individual entities for each from db. Has anybody done something like this before?

Dale K
  • 25,246
  • 15
  • 42
  • 71
Riz
  • 6,486
  • 19
  • 66
  • 106
  • Does this answer your question? [Entity Framework: Check all relationships of an entity for foreign key use](https://stackoverflow.com/questions/12851199/entity-framework-check-all-relationships-of-an-entity-for-foreign-key-use) – eocron Nov 04 '20 at 22:42
  • If you want to load all related entities - you are doomed. Never do this, you will download entire database at some point. – eocron Nov 04 '20 at 22:44
  • As you are using EF, does your `Person` entity have an `ICollection` or similar for `Cars` that are related? – NetMage Nov 05 '20 at 00:58

0 Answers0