Code-First Data Annotations将数据库列标记为不可为空,但允许空字符串 [英] Code-First Data Annotations mark database column as not-nullable, but allow empty string
问题描述
在LINQ2SQL中,我使用[Column]属性,"CanBeNull = false"。确保null未保存到数据库。如果我想禁止空字符串,我会使用[必需]属性。并且,这适用于MVC UI和模型/绑定验证。
与EF4相同的是什么? [Column]属性不再具有nullable属性,那么[Required]属性呢?如果我这样做,[必需(AllowEmptyString = true)],它会弄乱我的UI逻辑规则。
请帮助!
Ray,
你能否使用[Required]和[StringLength]的组合来获得你想要的可空性/字符串长度限制的组合?
如果没有,您可以避免使用[必需],而是使用流畅的API使数据库中的列不可为空。
例如:
modelBuilder.Entity< Foo >()。属性(a => a.MyProp).IsRequired();
谢谢,
Arthur 跨度>
In LINQ2SQL, I use to use the [Column] attribute, "CanBeNull = false" to ensure that null was not saved to the database. I would then use the [Required] attribute if I wanted to disallow empty strings. And, this worked will for MVC UI and model/binding validation.
What is the equivalent with EF4? The [Column] attribute doesn't have the nullable property anymore, and what about the [Required] attribute? If I do something like this, [Required(AllowEmptyString=true)], it will mess up my UI logic rules.
Help please!
Ray,
Can you use a combination of [Required] and [StringLength] to get the combination of nullability/string length restrictions that you want? If not, you could avoid using [Required] and instead use the fluent API to make the column non-nullable in the database. For example:
modelBuilder.Entity<Foo>().Property(a => a.MyProp).IsRequired();
Thanks,
Arthur
这篇关于Code-First Data Annotations将数据库列标记为不可为空,但允许空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!