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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With