验证复杂类型的DataAnnotations [英] Validate complex types with DataAnnotations

查看:120
本文介绍了验证复杂类型的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆