EF 5忽略Int类型的[Required]属性 [英] EF 5 Is Ignoring [Required] Attribute On Int Type
问题描述
当包含在int字段中时,Entity Framework 5.0.0似乎忽略[Required]属性,并自动包含0值而不是引发异常.但是,如果该字段是字符串,则required属性似乎确实起作用.下面的简单模型和创建函数不会引发任何异常.为简洁起见,未显示具有DbSet度的DbContext类.
Entity Framework 5.0.0 seems to ignore the [Required] attribute when included on an int field and automatically includes a 0 value instead of throwing an exception. The required attribute does seem to work if the field is a string though. The simple model and create function below throws no exceptions. DbContext class with DbSet Degrees not shown for brevity.
public class Degree
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
public int Field { get; set; }
}
private static void CreateDegree()
{
var degree = new Degree { Name = "Mechanical Engineering" };
var db = new Context();
db.Degrees.Add(degree);
// try statement
}
这对我来说可能是一个简单的误解,但是任何想法/帮助都将不胜感激.
This maybe a simple misunderstanding on my part, but any thoughts / help would be greatly appreciated.
推荐答案
[Required]
属性指示必须存在一个值.构造Degree
时,将Field
初始化为0,因为这是int
的默认值.由于0是一个值,因此它满足[Required]
属性.
The [Required]
attribute indicates that a value must be present. When a Degree
is constructed, Field
is initialized to 0 because that is the default value for int
s. Since 0 is a value, it satisfies the [Required]
attribute.
您可能想尝试使用[Range]
属性来指定该值必须大于0.或者您可以将模型更改为具有int?
,这样它将成为null
,除非将其初始化为一些价值.
You may want to try a [Range]
attribute to specify that the value must be greater than 0. Or you could change the model to have an int?
, so that it would be null
unless it got initialized to some value.
这篇关于EF 5忽略Int类型的[Required]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!