如何防止context.savechangs在必需的属性上抛出错误
我有这段代码来起草消息
这是控制器方法
public string DraftMessage(message draftMessage, string status, HttpPostedFileBase[] files = null)
{
ModelState.Remove("Title");
ModelState.Remove("Body");
if (ModelState.IsValid)
{
return new MessageActions().DraftMessage(draftMessage, status);
}
return "validation error";
}
这是模型方法
public string DraftMessage(message draftMessage, string status)
{
if (status == "new")
{
draftMessage = new message();
draftMessage.Status = "DR";
draftMessage.DateOfCreation = DateTime.UtcNow;
draftMessage.C_From = CurrentUser.Id;
context.messages.Add(draftMessage);
draftMessage.To = new int[2];
foreach (int receiverId in draftMessage.To)
{
if (context.users.Any(user => user.user_id == receiverId && (user.DepartmentOfTheUser.Company == CurrentUser.Company || user.DepartmentOfTheUser.CompanyOfTheDepartment.CompanyCustomers.Any(cus => cus.customer_of == CurrentUser.Company) || user.DepartmentOfTheUser.CompanyOfTheDepartment.CompanySuppliers.Any(supp => supp.supplier_of == CurrentUser.Company))))
{
context.MessageReceiversConnectors.Add(new MessageReceiversConnector() { MessageId = draftMessage.id, ReceiverId = receiverId, MessageStatus = "DR" });
}
}
}
context.SaveChanges();
return "draft";
}
我使用entityframework创建的相同实体来交换数据,我使用了使用所需的属性进行验证,请看下面的代码
[Required(ErrorMessage="This field is required")]
public int[] To { get; set; }
[Required(ErrorMessage = "This field is required")]
public string Title { get; set; }
[Required(ErrorMessage = "This field is required")]
public string Body { get; set; }
ModelState.Remove在控制器端工作,但是当我到达模型时,它会在context.savechanges上抛出异常。
有没有办法解决这个问题。
答案 0 :(得分:0)
我通过将此选项context.Configuration.ValidateOnSaveEnabled
设置为false来解决我的问题。