验证复杂类型的DataAnnotations [英] Validate complex types with DataAnnotations
问题描述
我已经决定使用实体框架的O / R映射,并在我的项目验证DataAnnotations,现在我也遇到过尝试实现这个当一个奇怪的问题。
I've decided to use Entity Framework for O/R Mapping, and DataAnnotations for validation in my project, and I have now encountered an odd problem when trying to implement this.
这是我干了什么:
我有以下实体类型
Contact
*******
Int32 Id (not null, Entity Key)
Name Name (not null)
Address Address (not null)
String Phone
String Email
其中,名称
和地址
是定义的复杂类型如下:
where Name
and Address
are complex types defined as follows:
Name Address
**** *******
String First (not null) String Street (not null)
String Last (not null) String ZipCode (not null)
String City (not null)
和下面的类驻留在同一个命名空间我的实体:
And the following classes reside in the same namespace as my entities:
public class ContactMetadata
{
[Required]
public Name Name { get; set; }
}
[MetadataType(typeof(ContactMetadata))]
partial class Contact { }
然而,当我创建一个新的联系
项中,名称
和地址
类型都充满了名称
和地址
,其中所有的值都是空
而不是名称
和地址
有空
值本身。因此,要求
属性不会引发任何错误,虽然所有值都空
。我该如何解决此问题?
However, when I create a new Contact
item, the Name
and Address
types are filled with instances of Name
and Address
where all values are null
, instead of Name
and Address
having null
values themselves. Thus, the Required
attribute doesn't throw any errors, although all values are null
. How do I work around this?
推荐答案
所以它创造的名称和地址的对象是谁属性是空的实例?有意思的。
So it creates instances of the Name and Address objects who's properties are null? Interesting.
你能不能只是把[必填]属性上孩子?
Can you just put the [Required] attribute on the children?
编辑:我知道这可能被认为是这样做的臭方式,但为了清楚起见我编辑你的答案进入后,使之能更容易有这个问题,旁边的人可以找到...
I know this might be considered a smelly way of doing this, but for clarity I edit your answer into the post, so that it can easier be found by the next person having problems with this...
建议(适用和接受,但尚未检验)解决方案:
Suggested (and accepted, but yet untested) solution:
写这验证对空
值的自定义验证属性。
Write a custom validation attribute which validates against the null
values.
这篇关于验证复杂类型的DataAnnotations的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!