EF Codefirst validate unique property?

2020-08-26 03:48发布

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

2条回答
The star\"
2楼-- · 2020-08-26 04:41

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

查看更多
▲ chillily
3楼-- · 2020-08-26 04:51

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.

查看更多
登录 后发表回答