简体   繁体   中英

How can I convert a one to many optional relationship to a one to one require relationship codefirst?

I have a database that contains a one-to-many relationship that is optional. I want to convert this relationship to a one-to-one required. For example one fish is required to have one tank to exist and once that fish has a tank no other fish can have that tank. But one tank can exist without one fish. I would like to preserve the data I have. My issue is when I try doing update-database; entity framework now sees that I have two id's which makes sense because the foreign key would become the primary key of the fish table. How can I work around this?

I'm using C# and SQL Server.

If it's truly going to be a one:one relationship, the easiest way to handle it is to store them in the same record: eg

CREATE TABLE Tank
(
    tank_id    Int IDENTITY NOT NULL,
    fish_id    Int NULL
)

(A tank with no fish would have a NULL fish_id value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM