Code snippet for throwing a sensible message instead of a Entity framweork validation exception (DbEntityValidationException)
When entity framework throws exceptions for data validation it does not clearly expose all the exceptions. This is what you must do to make get to them:
This is my code snippet to make it happen. Thanks to http://blogs.infosupport.com/improving-dbentityvalidationexception/ for the c# code.
catch(DbEntityValidationException ex)
{
IEnumerable<string> errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x
=> x.ErrorMessage);
throw new Exception(string.Join("; ", errorMessages))
}
This is my code snippet to make it happen. Thanks to http://blogs.infosupport.com/improving-dbentityvalidationexception/ for the c# code.
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>EntityFrameworkValidationCatch</Title>
<Shortcut>JCEntityFrameworkValidationCatch</Shortcut>
<Description>Catch for entity framwork validation errors</Description>
<Author>James Cooke</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[catch(DbEntityValidationException ex)
{
IEnumerable<string> errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>EntityFrameworkValidationCatch</Title>
<Shortcut>JCEntityFrameworkValidationCatch</Shortcut>
<Description>Catch for entity framwork validation errors</Description>
<Author>James Cooke</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="csharp">
<![CDATA[catch(DbEntityValidationException ex)
{
IEnumerable<string> errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
throw new Exception(string.Join("; ", errorMessages))
}$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
}$end$]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home