Error: Validation failed for one or more entities (C# MVC)
Usually this exception means the database is failing validation. This can occur if you have a set field in the database with a set character count and you are trying to save to that field a string which exceeds the database count.
Update your database string types with a 'varchar(max)' for example.
Hope this helps
Validation failed for one or more entities in Entity Framework for nullable boolean property
The issue here was boolean value cannot be configured as null. It will always be considered required by EF. I changed IsModified bit null
to IsModified bit not null default 1
.And updated the existing records with default value using Migration.
Reference - https://learn.microsoft.com/en-us/ef/core/modeling/required-optional.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. ASP.NET MVC
Look at your model definition
// This means this value is required
// and should not be greater than 255 characters
[Required]
[StringLength(255)]
public string PetName { get; set; }
// This means this value is required
// and should not be greater than 6 characters
[Required]
[StringLength(6)]
public string PetGender { get; set; }
So either you are not sending a value from your client app or it is larger than the restrictions you stated.
Change your action method to this to validate your model in your backend (you should never trust the client input)
[HttpPost]
public ActionResult Save(PetRescued petRescued)
{
if (ModelState.IsValid) // Check for errors
{
if (petRescued.Id == 0)
_context.PetRescueds.Add(petRescued);
else
{
var petRescuedInDb = _context.PetRescueds.Single(c => c.Id == petRescued.Id);
petRescuedInDb.PetName = petRescued.PetName;
petRescuedInDb.PetAge = petRescued.PetAge;
petRescuedInDb.PetGender = petRescued.PetGender;
petRescuedInDb.PetWeightInKg = petRescued.PetWeightInKg;
petRescuedInDb.PetSpeciesId = petRescued.PetSpeciesId; //strange
petRescuedInDb.DateWhenRescued = petRescued.DateWhenRescued;
}
_context.SaveChanges();
return RedirectToAction("Index", "PetRescued");
}
else
return View(petRescued); // Return the same view with the original data
// or with the correct model of your view, at least
}
UPDATE
Correct your view model to reflect your correct data. That means, make sure you are sending the correct model to the backend. ASP.Net MVC has something called Model Binding, which is the mechanism used to convert the data received from the client into your C# model. By default, it works by detecting the name of the values passed from the client and finding an exact mapping with the properties of the model. That means that in your view you are declaring this
@Html.TextBoxFor(m => m.PetRescueds.PetName, new { @class = "form-control" })
So, if you inspect the data sent by the browser you will see that the form data includes something like
PetRescueds.PetAge: whatever_the_client_typed
That will not be mapped to your model, because your model doesn't have a property named PetRescueds with a subproperty named PetName, your action model is directly a PetRescued model. So either change your view by specifying directly the name attr like this
@Html.TextBox("PetName", Model.PetRescueds.PetName, new { @class = "form-control" })
Or change your action model to reflect your view model definition. Either way, your view model should be consistent through your action and view. Otherwise, you will end up receiving null values in your action model in spite of filling them correctly on your view, or showing empty values in your views regardless of what you actually created on your controller action.
So, basically, check your model definitions. Make sure you are using a correct model definition to display in your views. Make sure your view is correctly defined as to what you are expecting to receive in your backend controller.
Then, change your view to include validation errors retrieved from the server
@using (Html.BeginForm("Save", "PetRescued"))
{
<!-- This will show your errors-->
@Html.ValidationSummary()
<div class="form-group">
@Html.LabelFor(m => m.PetRescueds.PetName)
<!-- Or you can show errors for each model property -->
<!-- like this -->
@Html.ValidationMessageFor(m => m.PetRescueds.PetName);
@Html.TextBox("PetName", Model.PetRescueds.PetName, new { @class = "form-control" })
</div>
//strange
<div class="form-group">
@Html.LabelFor(m => m.PetSpecies)
@Html.DropDownListFor(m => m.PetRescueds.PetSpeciesId, new SelectList(Model.PetSpecies, "Id", "SpeciesName"), "Select A Species", new {@class = "form-control"})
</div>
<div class="form-group">
@Html.LabelFor(m => m.PetRescueds.PetAge)
@Html.TextBoxFor(m => m.PetRescueds.PetAge, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.PetRescueds.PetGender)
@Html.TextBoxFor(m => m.PetRescueds.PetGender, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.PetRescueds.PetWeightInKg)
@Html.TextBoxFor(m => m.PetRescueds.PetWeightInKg, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.PetRescueds.DateWhenRescued)
@Html.TextBoxFor(m => m.PetRescueds.DateWhenRescued, "{0:d MMM yyyy}", new { @class = "form-control" })
</div>
@Html.HiddenFor(m => m.PetRescueds.Id)
<button type="submit" class="btn btn-primary">Save</button>
}
You can read more about data validation at Microsofts's
Validation error in Entity framework when inserting data into the database
You have to remove Required for this properties or create these lists before SaveChanges()
[ForeignKey("Movie")]
[Required]
public virtual List<Movie> Movies { get; set; }
[Required]
public virtual List<Series> Series { get; set; }
[Required]
public virtual List<Preference> Preferences { get; set; }
}
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. in mvc
This is usually an error with your entity framework while trying to perform a database operation. Here is a modified example from TechFunda showing how to see what your entity validation errors are so that you can fix them. If you look at the errorMessage varaible while debugging it should tell you what your actual error is.
public ActionResult ReceiveParameters(PersonalDetails pd)
{
try
{
//Entity Framework Code You are executing
}
catch (DbEntityValidationException ee)
{
foreach (var error in ee.EntityValidationErrors)
{
foreach(var thisError in error.ValidationErrors)
{
var errorMessage = thisError.ErrorMessage;
}
}
}
return View();
}
Source: TechFunda Article
validation failed for one or more entities Entity Framework in ASP .Net
The field PathToCover must be a string or array type with a maximum length of '4000'
Validation failed for one or more entities plus other error
Your product entity is creating a User entity. The User entity probably inherits from Identity class that requires a password. For inserts you will need to use a UserManager to add users, but since this is an update all you need to do is fetch the existing user attached to the product before updating:
Product product = context.Products.Include(p => p.User).Single(p => p.ProductId == SelectedProduct.Id);
product.Name = "Frank";
context.SaveChanges();
Related Topics
Format Timespan Greater Than 24 Hour
Get the Value for a Listbox Item by Index
System.Text.JSON API Is There Something Like Icontractresolver
Why Switch for Enum Accepts Implicit Conversion to 0 But No for Any Other Integer
Calling Function from Generated Button in Blazor
Databinding to List - See Changes of Data Source in Listbox, Combobox
Null or Default Comparison of Generic Argument in C#
Why Does Calling a Method in My Derived Class Call the Base Class Method
How to Fix "Referenced Assembly Does Not Have a Strong Name" Error
ASP.NET MVC Ambiguous Action Methods
Make a Sphere with Equidistant Vertices
How to Use a Reserved Keyword as an Identifier in My JSON Model Class
How to Convert an Escaped JSON String Within a JSON Object
Determine If a Sequence Contains All Elements of Another Sequence Using Linq