验证复杂类型的DataAnnotations
-
21-08-2019 - |
题
我已经决定使用实体框架的O / R映射,并在我的项目验证DataAnnotations,现在我也遇到过尝试实现这个当一个奇怪的问题。
这是我干了什么:
我有以下实体类型
Contact
*******
Int32 Id (not null, Entity Key)
Name Name (not null)
Address Address (not null)
String Phone
String Email
其中Name
和Address
是定义的复杂类型,如下所示:
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
项目时,Name
和Address
类型填充有Name
和Address
其中所有值都null
的实例,而不是Name
和Address
具有null
值本身。因此,Required
属性不会引发任何错误,但所有值都null
。如何解决此问题?
解决方案
所以它创造的名称和地址的对象是谁的性质是空的实例?有趣。
你能仅仅把[必需]属性上的孩子?
编辑:我知道这可能被认为是这样的臭路,但是为了清楚我编辑你的答案进入后,使之能更容易有这个问题,旁边的人发现......
<强>建议强>(和接受,但尚未检验)的溶液强>
收件这验证靠在null
值定义验证属性。
其他提示
请确保在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") %>
[...]
我用了同样的问题,现在挣扎。我认为,一个半优雅的方式来做到这一点是引用键原始类型的属性,并把dataannotation上。下面是与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;}
}
不隶属于 StackOverflow