问题描述
我有被映射到的ViewModels的DTO。为了避免管理验证属性(及其他属性),我想写一个单一类的所有属性的属性验证和重用它在我的ViewModels。然而,当我尝试使用元数据在不具备DTO的所有属性(所有的人都真的... ...)一个视图模型,它给了我一个 System.InvalidOperationException
例外。
例外:
乐德式métadonnéesassocié倒乐型MyProject.EntityViewModel'contient莱propriétés欧inconnus suivants冠军:AnotherProperty。 Vérifiez阙莱NOMS去CES membres记者辅助NOMS DESpropriétés杜类型的主体。
谷歌翻译:
类型'MyProject.EntityViewModel'相关的元数据的类型包含以下未知属性或字段:AnotherProperty。验证这些成员的名称相匹配的主要类型的属性的名称。
简单的例子:
公共类实体{
公共字符串A {搞定;组; }
公共字符串B {搞定;组; }
公共字符串C {搞定;组; }
}公共类EntityDTO {
公共字符串A {搞定;组; }
公共字符串B {搞定;组; }
公共字符串C {搞定;组; }
}//这个类是用来添加属性验证,输入相关的视图模型
公共类EntityInputValidation {
[需要]
公共字符串A {搞定;组; } [需要]
公共字符串B {搞定;组; } //注意,我们没有对C验证
}//这个类是一个ViewModel用于创建一个新的实体
[MetadataType(typeof运算(EntityInputValidation))]
公共类EntityCreateViewModel {
//必需的,因为我们使用的InputValidation元
公共字符串A {搞定;组; } //注意我们没有b属性在这里,即使我们使用具有这个属性必需属性的输入验证。这是异常的来源。 // C只需要在这个视图/视图模型
[需要]
公共字符串C {搞定;组; }
}
由于EntityViewModel没有 AnotherProperty
,它会抛出异常。有没有一种方法,以prevent呢?
我肯定会重新考虑直接在你的实体拥有这些注释。正如你已经可以看到,这将导致你的问题时,你需要使用实体中并不需要遵守这些验证规则的视图。这将有可能在长期内变得更糟,如果更多的意见加入其中使用您的实体。
pretty多少你拿出任何解决方案,以停止抛出异常将是一个黑客。
每个意见更新时间:
That is certainly a valid concern, and this is also a valid question to be asking. The problem is more that there is no well-defined solution, at least that I've found.
Taking a look at the inheritance idea, it seems reasonable at first. However, this is only going to work if your properties fit into neat groups, which from your updated question seems may not be the case.
Let's take a simple example:
public class LoginValidation
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}
You could then derive a view model from that:
public class ViewModelA : LoginValidation
{
public string SomeOtherProperty { get; set; }
}
However, this comes with a problem. What if you want to inherit another set of validation properties? You can't, as we're restricted to inheriting from one class. We also cannot inherit data annotations from interfaces:
So what if you need LoginValidation
and some dates validation for a specific view? You'd have to create an inheritance chain from both in an intermediary class, just to be able to inherit from that for your view model:
public class LoginAndDateValidation : LoginValidation
{
[Required]
public DateTime StartDate { get; set; }
[Required]
public DateTime EndDate { get; set; }
}
public class ViewModelA : LoginAndDateValidation
{
public string SomeOtherProperty { get; set; }
}
Do you see where this is going? This would turn into a complete mess. So, as I said earlier, this will only work if your properties fit into, and are used in, well-defined groups, but it doesn't seem that is the case in your scenario.
To finish up, let me just link to an answer Mystere Man posted a few years back that I've always liked: http://stackoverflow.com/a/8075115/729541
这篇关于我怎么能忽略来自MetadataType属性缺失的领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!