Reputation: 26682
I have an entity model with a base class ItemBase which defines an ID, a name and a few other properties. The "ID" column is the identity, the "Name" colum is an unique field in the base table. This base class is also defined as an abstract class. So yes, it is a table in the database, but in EF4 I cannot create instances of this base class.
And I have five different entities that inherit from the base class. (Item1, Item2...Item5) So all of them inherit the properties of ItemBase and additional properties are stored in an alternate table. One table per type. Quite nice, actually!
An object of type Item2 could have the same name as an object of Item5. This would cause a problem since they would both end up with a record in the ItemBase table, and the Name field would be in conflict. That's just nasty. So if the Item2 class contains brands of television manufacturers and Item5 contains lists of smartphone manufacturers then "Samsung" cannot be added in both entity sets.
I need a solution that will work around this problem, while keeping it simple. (And without adding the Name field to all child tables, because YUCK!) Suggestions?
Because "Name" is in the base table and defined as 'Unique', I will end up with conflicts when two different entity classes have the same name. I need a solution where "Name" is in the base table, yet it's unique per child class only, not unique for the base class...
I could alter the child entities to add a prefix to the name when writing to the table, and removing it again when reading from the table. Or I add another field to the base table indicating the child class linked to it, and make "name"+"link" unique, instead of just "Name". Both solutions aren't very pretty and it's unclear to me how to implement one of those. So is there a better solution or else, how do I implement this nicely?
Upvotes: 0
Views: 185
Reputation: 364349
It cannot be solved by unique column. The unique key would need to be placed over two columns - one specifying the Name and one specifying the type of derived entity but that is not possible with the inheritance type you selected (Table-per-type) because EF will not create and maintain that additional column for you. That would be possible only with Table-per-hierarchy inheritance where all five child entities are stored in the same table as base class and there is discriminator column to differ among them.
To solve this with your current design you must either use trigger on base table with some query logic to find if name is unique per child or handle this completely in your application.
Upvotes: 3