我有映射到 ViewModel 的 DTO。为了避免必须管理验证属性(和其他属性),我想为单个类上的所有属性编写验证属性,并在我的 ViewModel 上重用它。但是,当我尝试在不具有 DTO 的所有属性的 ViewModel 上使用元数据(所有这些属性真的......)时,它给了我一个System.InvalidOperationException
例外。
例外:
Le type de métadonnées associé pour le type 'MyProject.EntityViewModel' contient les propriétés ou champs inconnus suivants : AnotherProperty. Vérifiez que les noms de ces membres correspondent aux noms des propriétés du type principal.
谷歌翻译:
The type associated metadata for type 'MyProject.EntityViewModel' contains the following unknown properties or fields: AnotherProperty. Verify that the names of these members match the names of the properties of the main type.
简化示例:
public class Entity {
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
public class EntityDTO {
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
//This class is used to add validation attributes for input-related view models
public class EntityInputValidation {
[Required]
public string A { get; set; }
[Required]
public string B { get; set; }
//Notice that we dont have a validation for C
}
//This class is a ViewModel used to create a new Entity
[MetadataType(typeof(EntityInputValidation))]
public class EntityCreateViewModel {
//Required because we use the InputValidation metadata
public string A { get; set; }
//Notice that we do not have the B property here, even if we are using the Input Validation which has a required attribute for this property. This is where the exception comes from.
//C is only required in this View/ViewModel
[Required]
public string C { get; set; }
}
因为 EntityViewModel 没有AnotherProperty
,所以会抛出异常。有没有办法防止这种情况?