Entity Framework - Reverse Foreign Key Check

2019-04-15 14:33发布

问题:

We have a system that allows Administrators to build out new content types within the system, including foreign key linkages to other tables. The Admin can then rebuild the database, at which point it creates the tables and all the necessary relationships, then rebuilds the EDMX and recompiles everything. Works like a champ (I didn't write it or I might know the answer to this).

One drawback that we have is when a user goes to delete a record that may be linked to by an item in another table. This throws an error due to referential integrity. I'm trapping this, of course, but all I can provide right now is a generic 'You can't delete this item because it is linked to something' type of error. I would much rather check to see if the item is deletable and disable the button if not.

Is there a way that I can determine to what table/row the to-be-deleted item is linked, at runtime? Normally, I'd just query the related tables but due to the nature of this app, I don't know what those other tables would be at design-time.

So in short, if I have:

Foo: FooID, FooName Bar: BarID, FooID, BarName Pow: PowID, FooID, PowName

Is it possible to tell at runtime that a row in Foo cannot be deleted due to a FK linkage from either Bar or Pow and, if so, can I then tell which table is causing the error?

Thanks in advance; first posting here so please excuse any etiquette flubs :).

回答1:

You must query metadata and get list of all navigation properties

ObjectSet = context.CreateObjectSet<YourEntityType>();

// Get entity set for current entity type
var entitySet = ObjectSet.EntitySet;
// Get name of the entity's navigation properties
_propertyNames = ((EntityType)entitySet.ElementType).NavigationProperties.Select(p => p.Name).ToArray();

Now you have properties which must be checked before deletion. To check properties you must load those members and you must check if related entity exists. Both will probably require a lot of reflection which will affect performance of your application.

I have to say that your application architecture is horrible. It is like an example: where should EF not be used or how should EF not be used.