简体   繁体   中英

Entity constraint “check” with code-first

I made a table to associate a store with Table1 OR Table2 (and other infos)

Id
IdStore_FK
IdTable1_FK
IdTable2_FK
SomeOtherFieldsThatDoesntMatterRightNow

And I created a check constraint to make sure that it will NEVER have both FK's filled at the same time, and only one of them must be filled (XOR):

ALTER TABLE TABLE0 ADD CHECK ((IdTable1_FK IS NULL AND IdTable2_FK IS NOT NULL) OR (IdTable1_FK IS NOT NULL AND IdTable2_FK IS NULL))

But I ran that alter table manually after my add-migration and update-database . I need to develop those restrictions with code-only, to be able to send to my manager.

How can I tell entity framework to create that using only my code?
Is there any DataAnnotation to do that?

I tried to add modelBuilder.Sql("ALTER TABLE XXX....") inside the method Up of an specific migration. I can only add that line to the migration file after the add-migration , which creates the file.

A seed query after every startup checking if the constraint exists, and creating it if don't does not seems cool to me. Also it'll run only if I run the code, and not with the migration/update-database.

There is no way to do it using just code. However, you can leverage the EF migration process to run arbitrary SQL . You can also run sql during the database initialization in case you need to start with a fresh database.

That being said, a custom validation attribute might still be a good idea so that you can catch errors earlier.

Sorry for the meta answer, but these are resources that have helped me in the past.

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