Entity Framework 中错误“Validation failed for one or more entities. See 'EntityValidationErrors' property for more details”
大家好!我是 C# 和 Entity Framework 的新手,使用的是 4.1 版本。尝试通过 `SaveChanges()` 将数据保存到数据库时,总是抛出异常,内容为:“Validation failed for one or more entities. See 'EntityValidationErrors' property for more details”。
这是我的代码:
```csharp
using (var context = new MyDbContext())
{
var user = new User
{
Name = "John",
Email = "", // 空字符串
Age = -5, // 负值
CreatedDate = DateTime.Now
};
context.Users.Add(user);
context.SaveChanges(); // 这里出错
}
```
User 模型如下:
```csharp
public class User
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Range(0, 120)]
public int Age { get; set; }
public DateTime CreatedDate { get; set; }
}
```