[英]Can't update data in database because of Entity validation exception - ASP.Net MVC
我希望更新数据库中三个相关表中的数据。 我实际上正在将所有需要的数据发送到数据库,但是无法成功更新它们。 我得到了[DbEntityValidationException:对一个或多个实体的验证失败。 有关更多详细信息,请参见'EntityValidationErrors'属性。] SQL异常。
以下是我实际拥有的
ViewModel ChauffeurVM:
public class ChauffeurVM
{
public int ChauffeurId { get; set; }
public virtual PERSONNE Personne { get; set; }
public virtual PIECEIDENTITE PieceIdentite { get; set; }
public string NumeroPermis { get; set; }
}
控制器:
public ActionResult ModifierChauffeur(ChauffeurVM ChauffeurVM, HttpPostedFileBase postedPhoto, string Sexe)
{
CHAUFFEUR chauffeur = new CHAUFFEUR();
ChauffeurVM.Personne.Sexe = Sexe;
using (IDAL dal = new Dal())
{
ChauffeurVM.Personne.Photo = dal.UploadandGetImagePath(postedPhoto);
chauffeur.ChauffeurId = dal.UpdateChauffeur(ChauffeurVM);
return RedirectToAction("ListeChauffeur");
}
}
Dal方法:
public int UpdateChauffeur(ChauffeurVM chauffeur)
{
CHAUFFEUR c = new CHAUFFEUR();
try
{
c = ChauffeurParId(chauffeur.ChauffeurId);
c.NumeroPermis = chauffeur.NumeroPermis;
bdd.Entry(c).State = EntityState.Modified;
bdd.SaveChanges();
}
catch
{
throw;
}
//Try to assign the value chauffeur.Personne.PersonneId to the pId
int pId = chauffeur.Personne.PersonneId;
c.Personne = new PERSONNE();
PERSONNE p = detailsChauffeurparPersonneId(chauffeur.Personne.PersonneId);
try
{
if (p != null)
{
p.Nom = chauffeur.Personne.Nom;
p.Prenom = chauffeur.Personne.Prenom;
p.Sexe = chauffeur.Personne.Sexe;
p.Telephone = chauffeur.Personne.Telephone;
p.Photo = chauffeur.Personne.Photo;
p.LieuNaissance = chauffeur.Personne.LieuNaissance;
p.DateNaissance = chauffeur.Personne.DateNaissance;
p.CodePostal = chauffeur.Personne.CodePostal;
p.Adresse = chauffeur.Personne.Adresse;
p.Email = chauffeur.Personne.Email;
p.AdresseBoulot = chauffeur.Personne.AdresseBoulot;
p.AdresseDomicile = chauffeur.Personne.AdresseDomicile;
p.PersonneId = chauffeur.Personne.PersonneId;
bdd.Entry(p).State = EntityState.Modified;
bdd.SaveChanges();
}
else
{
}
}
catch
{
throw;
}
try
{
PIECEIDENTITE pi = detailsPieceIdentiteparPersonneId(chauffeur.Personne.PersonneId);
pi.NumeroPiece = chauffeur.NumeroPiece;
pi.LieuDelivrance = chauffeur.LieuDelivrance;
pi.DateDelivrance = chauffeur.DateDelivrance;
pi.DateExpiration = chauffeur.DateExpiration;
pi.Autorite = chauffeur.Autorite;
bdd.Entry(pi).State = EntityState.Modified;
bdd.SaveChanges();
}
catch
{
throw;
}
return c.ChauffeurId;
}
我希望更新数据库中的数据。 但是我收到以下异常:[DbEntityValidationException:对一个或多个实体的验证失败。 有关更多详细信息,请参见'EntityValidationErrors'属性。
添加断点时,我成功捕获了从表单发送的所有数据。 我不知道哪个字段具有空值。
请帮助!
您有一个DbEntityValidationException,它应将您指向引起此问题的成员。 您应该按如下所示捕获DbEntityValidationException来获取验证消息。 在EntityValidationErrors列表中查找更多信息。
try
{
}
catch(DbEntityValidationException ex)
{
var firstErrorMessage = ex.EntityValidationErrors.First().ValidationErrors.First()
.ErrorMessage;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.