Entity Framework - checking the reverse foreign key

We have a system that allows administrators to create new types of content within the system, including foreign keys for other tables. Then the administrator can restore the database, after which it creates tables and all the necessary relationships, then restores EDMX and recompiles everything. Works like a champion (I did not write it, or I might know the answer to this question).

One of the drawbacks that we have is when the user proceeds to delete a record to which an element in another table can be bound. This causes an error due to referential integrity. Of course, I trap this, but all I can provide right now is the general "You cannot delete this element because it is associated with something." I would prefer to check if the item has been deleted and disable the button if not.

Is there a way by which you can determine which table / row the item to be deleted is associated with at run time? I usually just query related tables, but due to the nature of this application, I don’t know what these other tables will be during development.

So, if I have:

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

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

Thanks in advance; send here first, please excuse any labels :).

+1
source share
1 answer

You should request metadata and get a 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 navigation properties
_propertyNames = ((EntityType)entitySet.ElementType).NavigationProperties.Select(p => p.Name).ToArray();

You now have properties that you need to verify before deleting. To check properties, you must load these elements, and you must check if the associated object exists. Both will probably require a lot of thought that will affect the performance of your application.

, . : EF EF .

+2

All Articles