要点:
当我想更新数据库中的Model实例时,会导致Field is required
字段的验证错误Client
(在保存之前填充Altough字段,在跟踪程序时不填空)。
详细信息:
我有一个模型Project
,如下所示:
namespace ProjectManager.Models
{
public class Project
{
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "نام پروژه")]
[StringLength(100, MinimumLength = 5, ErrorMessage = "{0} باید حداقل {2} و حداکثر {1} کاراکتری باشد")]
public string Name { get; set; }
[Display(Name = "کارفرما")]
[Required]
public virtual ApplicationUser Client { get; set; }
[ForeignKey("Client")]
public string ClientId{ get; set; }
[Display(Name = "مدیر پروژه")]
[Required]
public virtual ApplicationUser ProjectManager { get; set; }
[ForeignKey("ProjectManager")]
public string ProjectManagerId{ get; set; }
[Range(0,100)]
[Display(Name = "پیشرفت پروژه")]
[Required]
public int Progress { get; set; }
[DataType(DataType.Date)]
[Display(Name = "تاریخ ثبت پروژه")]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreateDate { get; set; }
//[Required]
[Column("Disabled")]
[Display(Name = "غیرفعال")]
public bool Disabled{ get; set; }
//[Required]
[Column("Status")]
[Display(Name = "وضعیت")]
public string Status{ get; set; }
//-------------------- Payment Requests of Projects
public virtual ICollection<PaymentRequest> PaymentRequests { get; set; }
public virtual ICollection<Contract> Contracts { get; set; }
}
}
当我想更改项目进度时,我使用以下控制器:
public ActionResult UpdateProgress()
{
ApplicationUser projectManager = db.Users.Find(User.Identity.GetUserId());
Project project = Utils.getProjectManagerProject(projectManager, db);
EditProgressProjectViewModel model = new EditProgressProjectViewModel
{
Progress = project.Progress
};
return View(model);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UpdateProgress(EditProgressProjectViewModel projectModel)
{
if (projectModel == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
if (ModelState.IsValid)
{
ApplicationUser projectManager = db.Users.Find(User.Identity.GetUserId());
Project project = Utils.getProjectManagerProject(projectManager, db);
project.Progress = projectModel.Progress;
try
{
db.SaveChanges();
}
catch (DbEntityValidationException e)
{
Utils.addValidationErrorsToModelState(ModelState, e);
return View(projectModel);
}
return RedirectToAction("Index");
}
return View(projectModel);
}
}
但是尝试运行db.saveChanges()导致验证错误,说“需要字段客户端”,但是project.client不为空,并且填充了已从数据库获取的值。
答案 0 :(得分:2)
问题是[Required]
定义在不好的地方,
它意味着代替这个宣言:
[Display(Name = "کارفرما")]
[Required]
public virtual ApplicationUser Client { get; set; }
[ForeignKey("Client")]
public string ClientId{ get; set; }
必须使用:
[Display(Name = "کارفرما")]
public virtual ApplicationUser Client { get; set; }
[ForeignKey("Client")]
[Required] //**** Right Place for required annotation****
public string ClientId{ get; set; }
[Required]
应放置ForeignKey
ID而不是ForeignKey
对象。