Can I get Entity Framework (model-first) to generate composite keys?

牧云@^-^@ 提交于 2019-12-08 02:41:40

问题


I am designing a database using Entity Framework's "model-first" approach. Based on excellent feedback I recieved here, I am adopting a super-type/sub-type pattern for part of the DB.

This pattern requires composite keys based on 2 columns in at least 2 tables (see schema below).

I've searched the forum for "entity framework" and "composite keys", but none of the questions I found were on this more basic level: Can I set up an entity model so that it will generate one table (using "Generate Database from Model...") with a composite primary key on 2 columns, such that one is a foreign key on a second table? And on another table, the same situation except the FK is based on 2 columns in the first table?

OR, is it better to just let EF generate the DB w/o the composite keys, then go into SQL Server, (re-)set the primary keys, delete the model, & create a new model based on the newly instantiated database? I know how to do that, of course; but as I'm still working out a minor detail or 2 in the DB structure, I'd prefer to put off anything that essentially results in baking in the DB structure at this point.

Here's the recommended super-type/sub-type structure, which I've mirrored in my entity model (w/o yet figuring out how to get the composite keys generated):

CREATE TABLE publications (
  pub_id INTEGER NOT NULL PRIMARY KEY,
  pub_type CHAR(1) CHECK (pub_type IN ('A', 'B', 'P', 'S')),
  pub_url VARCHAR(64) NOT NULL UNIQUE,
  CONSTRAINT publications_superkey UNIQUE (pub_id, pub_type)
);


CREATE TABLE articles (
  pub_id INTEGER NOT NULL,
  pub_type CHAR(1) DEFAULT 'A' CHECK (pub_type = 'A'),
  placeholder CHAR(1) NOT NULL, -- placeholder for other attributes of articles
  PRIMARY KEY (pub_id, pub_type),
  FOREIGN KEY (pub_id, pub_type) REFERENCES publications (pub_id, pub_type)
);

CREATE TABLE stories (
  pub_id INTEGER NOT NULL,
  pub_type CHAR(1) DEFAULT 'S' CHECK (pub_type = 'S'),
  placeholder CHAR(1) NOT NULL, -- placeholder for other attributes of stories
  PRIMARY KEY (pub_id, pub_type),
  FOREIGN KEY (pub_id, pub_type) REFERENCES publications (pub_id, pub_type)
);

回答1:


I didn't try it but I think you will not be able to create this with model first. The reason is that your first table is using Unique constraint and your second and third table is building FK based on that constraint. Entity framework does not support Unique constraints so my assumption is that it will not be able to generate this DB schema. But nothing is more easy then simply try it.



来源:https://stackoverflow.com/questions/5261298/can-i-get-entity-framework-model-first-to-generate-composite-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!