AtLeastTheresToast
AtLeastTheresToast

Reputation: 387

DbEntityValidationException unhandled by user code

I am making an MVC .Net application and I have have trouble understanding why my db.SaveChanges(); is not working and creating an validation error. I have been looking through stack but I am having trouble finding a solid explanation of this problem.

This is my controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include"Id, EventTitle, EventSubTitle, EventAddress,EventCity,EventState,EventZip,EventCreator,EventTime,EventDiscription")] Event @event, AspNetUser @user)
{
if (ModelState.IsValid)
{
@event.Id = Guid.NewGuid();
@event.EventCreator = @user.Id;
db.Events.Add(@event);
db.SaveChanges();
return RedirectToAction("Index");
}

My thought is that the user.Id needs to be connected to the Event model to validate but I thought I would ask.

Thanks guys.

Upvotes: 0

Views: 2912

Answers (1)

Errore Fatale
Errore Fatale

Reputation: 988

DbEntityValidationException to my experience is thrown when there are problems similar to the followings:

  • The size of data inside one or more entities is greater than the one accepted inside the database. For example, if in your database you have a table Person with Name Varchar(20) and in the entity you are trying to save you have a name longer than 20, the exception will be thrown

  • You are trying to add an entity with a primary key which already exists

  • Violation of a foreign key or other things which relate to your database

How to avoid this exception? Validate your data before to save it in the database. It seems that you are doing it with ModelState.IsValid, but we don't see the code for the validation process. Check that validation is correct, inline with the rules of your database.

Note: in a professional application, usually you don't call DbContext directly from your controller.

Upvotes: 1

Related Questions