使用DataAnnotations验证复杂类型

时间:2009-06-30 03:19:42

标签: asp.net-mvc entity-framework data-annotations

我决定在我的项目中使用实体框架进行O / R映射和DataAnnotations进行验证,我现在在尝试实现时遇到了一个奇怪的问题。

这就是我所做的:

我有以下实体类型

Contact
*******
Int32 Id (not null, Entity Key)
Name Name (not null) 
Address Address (not null)
String Phone
String Email

其中NameAddress是复杂类型,定义如下:

Name                                  Address
****                                  *******
String First (not null)               String Street (not null)
String Last (not null)                String ZipCode (not null)
                                      String City (not null)

以下类与我的实体位于同一名称空间中:

public class ContactMetadata
{
    [Required]
    public Name Name { get; set; }
}

[MetadataType(typeof(ContactMetadata))]
partial class Contact { }

但是,当我创建新的Contact项时,NameAddress类型会填充NameAddress的实例,其中所有值均为null代替NameAddress自己拥有null个值。因此,Required属性不会抛出任何错误,尽管所有值都是null。我该如何解决这个问题?

4 个答案:

答案 0 :(得分:1)

那么它会创建Name和Address对象的实例,这些对象的属性为null?有趣。

你能把[必需]属性放在孩子身上吗?

编辑:我知道这可能被认为是这样做的一种臭方式,但为了清楚起见,我将你的答案编辑到帖子中,以便下一个有问题的人可以更容易地找到它...

建议(已接受但未经测试)解决方案

编写一个自定义验证属性,该属性根据null值进行验证。

答案 1 :(得分:1)

确保最终在HTML字段中的名称与该类的属性名称对齐。

例如,如果你有这个:

public class Contact {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Address Address { get; set; }
}

public class Address {
    public string Street { get; set; }
    public string City { get; set; }
    [...]
}

您对HTML帮助程序的调用应如下所示:

<%= Html.TextBox("FirstName") %>
<%= Html.TextBox("LastName") %>
<%= Html.TextBox("Address.Street") %>
<%= Html.TextBox("Address.City") %>
[...]

答案 2 :(得分:0)

查看此博文complex-dataannotations-validation。我认为RequiredAssociation属性是您所需要的。您可能需要为Entity Framework而不是LINQ to SQL稍微调整一下。

答案 3 :(得分:0)

我现在正在努力解决同样的问题。我认为一种半优雅的方法是将关键基元类型作为属性引用,并将数据注释放在其上。以下是AddressID作为关键字段的示例。

public class Contact{

[Required]
public int? AddressIDForValidation{
get{return this.Address.AdressID;}
}

public Address Address{get;set;}
}



public class Address{
public int? AddressID{get;set;}
public string Street{get;set;}
}