Assume a simple blog-like scenario, where posts are stored both by id and a SEO friendly slug. Is there a way to check that the slug doesn’t already exist during insert? I mean, I could always do something like:
var check = context.Posts.SingleOrDefault(p => p.slug == slug);
if (check != null)
{
// slug already exists - modify or throw exception
}
else
{
// save as normal
}
But that seems woefully inelegant to me. I assume there’s a better way, but am unsure of what it would be.
You could just set the
UNIQUE CONSTRAINTon the appropriate table in the underlying database.