EF Codefirst validate unique property?

人走茶凉 提交于 2019-12-22 04:21:02

问题


Curious about how to efficiently validate that a given property of a CodeFirst model is unique. Classic example being a member's username or display name.

Traditionally I might do this by setting a Unique constraint in the database, or alternatively by doing a lookup during an attempted insert operation. I know how to manually add these things in the DB itself after generation, just wanting to see if there's a way to do it as part of the schema mapping provided by the framework.

UPDATE I found that I can override the ValidateEntity method on the DbContext, which conceptually would allow me to do a lookup and then invalidate the object to prevent the save. I'd still be curious to know if there's a way to apply a Unique constraint or similar in the database


回答1:


Code First (and EF in general) still does not natively support unique constraints. In this post I showed one way to create them at the same time that your database is get created by Code First (via SQLCommand method in a custom Initializer class) but it's not really different from manually creating it yourself. The other way is ValidateEntity which you've suggested, but I would still create the unique constraints on the database anyways.




回答2:


I have posted about this at code project

In general, it depends on the attributes that you put on the classes to generate your unique indexes



来源:https://stackoverflow.com/questions/4914847/ef-codefirst-validate-unique-property

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