Major Productions
Major Productions

Reputation: 6062

EF4 - insert only if a column has a unique value?

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.

Upvotes: 0

Views: 99

Answers (2)

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

you should avoid to throw exceptions when is possible and use them only to handle "proper" exceptions which means something you could avoid to happen.

There is nothing wrong with your code anyway

Upvotes: 0

tsionyx
tsionyx

Reputation: 1669

You could just set the UNIQUE CONSTRAINT on the appropriate table in the underlying database.

Upvotes: 2

Related Questions