Per excellent advice I received on a recent question (Database design problem),
I am incorporating a super-type/sub-type pattern in a DB I’m
building for an MVC2 app.
I’ll be using Entity Framework to provide the models to MVC.
The super-type is Publications, while the sub-types are Articles,
BlogPosts, etc.
Each sub-type table will have a 2-column composite primary key (pub_id,
pub_type), with foreign keys that reference corresponding columns in the
super-type table
For data integrity purposes (see lengthy comments on accepted solution
to original question) the super-type table should not include the
pub_type in its primary key (unlike the sub-type tables),
And that is where Entity Framework doesn’t seem to play along. Warnings I get when I generate the .edmx file from my existing database:
The relationship ‘FK_Articles_Publications’ has columns that are not
part of the key of the table on the priamry side of the relationship. The relationship was excluded.
(etc.)
QUESTION:
is there any way to coax Entity Framework into mapping the relationship given
the foreign keys I want (or will I have to compromise the DB design and
set a composite key on the supertype table)?
If not, this adds the additional problem of requiring that joing any
other, non-sub-type table (and I plan on several) to the super-type
table requires that I have columns corresponding to both pub_id and
pub_type. For example, I want a topics table to be able to associate
with any kind of publication via the super-type table — I would need
to store (redundantly) the pub_type in a column in the topics table.
I am quite new to EF (and ORM), but it’s power is alluring, and I don’t want to give it up.
In this table,
it matters that {pub_id} is unique and that {pub_id, pub_type} is unique. (The column pub_type should also be declared
NOT NULL.) In the first case, uniqueness guarantees identity. In the second case, uniqueness guarantees that subtypes reference the right kind of row in the supertype. But it doesn’t matter much to the database engine which one is declaredPRIMARY KEYand which one is declaredUNIQUE. Both can be the target of foreign key references.If a dbms were designed around current relational theory, it might support only
KEYdeclarations instead ofPRIMARY KEYandNOT NULL UNIQUE.So if your ORM can’t cope with constraints the way they’re written, it’s ok to make {pub_id} the primary key in all those tables, and to declare the reducible superkey {pub_id, pub_type} to be unique in all those tables.
I don’t know whether that will silence EF. You should test tables that reference the subtypes as well as tables that reference the supertype.