当我使用 Validator.TryValidateObject 时验证不起作用
DataAnnotations 不适用于伙伴类。以下代码始终验证 true。为什么 ?
var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);
这是好友类。
public partial class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
public class CustomerMetaData
{
[Required(ErrorMessage = "You must supply a name for a customer.")]
public string Name { get; set; }
}
}
这是另一个有同样问题的帖子,但没有答案。 链接文本
DataAnnotations does not work with buddy class. The following code always validate true. Why ?
var isValid = Validator.TryValidateObject(new Customer(), Context, results, true);
and here is the buddy class.
public partial class Customer
{
public string Name { get; set; }
public int Age { get; set; }
}
[MetadataType(typeof(CustomerMetaData))]
public partial class Customer
{
public class CustomerMetaData
{
[Required(ErrorMessage = "You must supply a name for a customer.")]
public string Name { get; set; }
}
}
Here is another thread with same question., but no answer.
link text
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在这里找到了答案: http://forums.silverlight.net/forums/p /149264/377212.aspx
MVC 识别 MetaDataType 属性,但其他项目不识别。在验证之前,需要手动注册元数据类:
I found the answer here: http://forums.silverlight.net/forums/p/149264/377212.aspx
MVC recognizes the MetaDataType attribute, but other projects do not. Before validating, you need to manually register the metadata class:
经过一番研究,我找不到任何原因,如果我使用 MetadataType (伙伴类),TryValidateObject 总是返回 true。但它适用于以下代码(xVal)。
After some research I couldn't find any reason why TryValidateObject always return true if I use MetadataType (buddy class). But it works with the following code (xVal).
虽然我没有在 .NET 4.0 中测试您的代码,但在 .NET 3.5 / Silverlight 3 中,您的元数据类应该如下所示:
Although I did not test your code in .NET 4.0, in .NET 3.5 / Silverlight 3, your metadata class should look like this:
存在一个问题:对象上下文无法识别 MetadataType 属性。虽然您可以在验证之前手动添加类型描述符:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetaData)), typeof(Customer));
更简洁的处理方法是更新实体模型 .tt 文件,将以下内容添加到每个 DTO:
这将允许您将属性添加到部分类中:
There is an issue where the MetadataType attribute is not being recognized by the object context. While you can manually add the type descriptor before validation:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Customer), typeof(CustomerMetaData)), typeof(Customer));
a more concise way to handle it would be to update the Entity Model .tt file, to add the following to each DTO:
This will allow you to add the attributes to the partial classes: