简体   繁体   English

实体约束“检查”代码优先

[英]Entity constraint “check” with code-first

I made a table to associate a store with Table1 OR Table2 (and other infos) 我创建了一个表来将商店与Table1或Table2(和其他信息)相关联

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): 我创建了一个检查约束,以确保它不会同时填充两个FK,并且只能填充其中一个(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 . 但是在我的add-migrationupdate-database之后我手动运行了alter table 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? 有没有DataAnnotation可以做到这一点?

I tried to add modelBuilder.Sql("ALTER TABLE XXX....") inside the method Up of an specific migration. 我试图在特定迁移的方法Up中添加modelBuilder.Sql("ALTER TABLE XXX....") I can only add that line to the migration file after the add-migration , which creates the file. 我只能在创建文件的add-migration 之后将该行add-migration文件中。

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 . 但是,您可以利用EF迁移过程来运行任意SQL You can also run sql during the database initialization in case you need to start with a fresh database. 您还可以在数据库初始化期间运行sql ,以防需要从新数据库开始。

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. 对于元回答感到抱歉,但这些资源在过去帮助了我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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