DbContext
验证错误传回客户端。我知道Breeze有默认的验证器可以反应出一些属性例如 Required
,但其他属性呢?我可以为Breeze编写一个自定义的JavaScript验证器,用于在客户端进行检查,但我还需要检查确保实体在服务器端是有效的。举个例子,该应用程序要求
Person
具有有效的电子邮件地址。恶意用户会提供一个通过客户端并能提交到服务器的电子邮件地址,但这个数据不会通过 EmailAddress
验证器。迄今为止,我的经验是Breeze将保存电子邮件地址并不弹出任何 DbContext
Entity Framework 错误。假设以下模型,如何获得任何实体验证错误?
public class PeopleContext : DbContext
{
public PeopleContext()
: base("name=ConnectionString"){ }
public DbSet<Person> People { get; set; }
}
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[EmailAddress]
[Required]
public string Email { get; set; }
}
更新1:
以下是重现我遇到问题的步骤。
- Follow the instructions to create the "Todo" sample (http://www.breezejs.com/documentation/start-nuget)
Add a new custom validator to the
BreezeSampleTodoItem.cs
file:[AttributeUsage(AttributeTargets.Property)] public class CustomValidator : ValidationAttribute { public override Boolean IsValid(Object value) { string val = (string)value; if (!string.IsNullOrEmpty(val) && val == "Error") { ErrorMessage = "{0} equal the word 'Error'"; return false; } return true; } }
Decorate the
Description
field with the new custom validator:[CustomValidator] public string Description { get; set; }
Add the proper
using
s of course (System
andSystem.ComponentModel.DataAnnotations
).- Run the project.
- In one of the description fields type "Error" and save.
throw new InvalidOperationException("无法保存未知类型的实体");
仅返回false告诉ContextProvider在保存期间跳过该实体;它并不能终止保存!详见文档中的 "Server-side interception" 页面。 - Ward