System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entitie

Posted by Sheonarayan under Error and Solution on 4/23/2014 | Points: 10 | Views : 11784 | Status : [Administrator] | Replies : 2

Proplem

I was getting this error while working with ADO.NET Entity Framework

System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Solution


To solve this error, we can wrap the SaveChanges() method of DatabaseContext object in try block and in the Catch loop through each errors to find out where is the error. The code goes below.

try
{
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}


Once the error is found, you can work on that to fix it.

Hope it helps.

Thanks

Regards,
Sheo Narayan
http://www.dotnetfunda.com



Responses

Posted by: Ektac on: 7/9/2014 [Member] Starter | Points: 25

Up
0
Down
i got same error but different issue. i just try to bound database data but i got this error.

in default.aspx

<h2>Categories</h2>
<div id="CategoryMenu" >
<asp:ListView ID="categoryList"
ItemType="abc.Models.Category"
runat="server" SelectMethod="GetCategories">
<ItemTemplate>
<b style="font-size:large; font-style:normal">
<a href="<%#: GetRouteUrl("ProductByCategoryRoute", new{categoryName=Item.CategoryName})%>">
<%#: Item.CategoryName %>
</a>
</b>
</ItemTemplate>
</asp:ListView>


and in default.aspx.cs


public IQueryable<abc.Models.Category> GetCategories()
{
var db = new abc.Models.ProductContext();
IQueryable<Category> query = db.Categories;
return query;

}


can you plz tell me actual where do i coding for try and catch for the 'EntityValidationErrors'

Sheonarayan, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Hassaan on: 10/19/2014 [Member] Starter | Points: 25

Up
0
Down
thank for the help , keep helping others too

Sheonarayan, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response