Question

How can I handle duplicate key row with unique index SqlException using [Index(IsUnique = true)] attribute in entity framework 6.1?

Was it helpful?

Solution

So here is a quick hack

try
{
    context.SaveChanges();
}
catch (DbUpdateException e)
{
    SqlException innerException = null;
    Exception tmp = e;
    while(innerException == null && tmp!=null)
    {
        if (tmp != null)
        {
            innerException = tmp.InnerException as SqlException;
            tmp = tmp.InnerException;
        }

    }
    if (innerException != null && innerException.Number == 2601)
    {
        // handle exception
    }
    else
    {
        throw;
    }
}

I hope there is a better solution...

OTHER TIPS

You can override the ValidateEntity in your dbContext and do your logic here.

I've posted about generic way how to do it in CodeProject

Validate a Unique Constraint at dbContext ValidateEntity in Entity Framework

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top