Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Codefirst validate unique property?

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

like image 723
Paul Avatar asked Feb 06 '11 17:02

Paul


1 Answers

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.

like image 192
Morteza Manavi Avatar answered Jan 02 '23 07:01

Morteza Manavi