1

ViewModel にマップされた DTO があります。検証属性 (およびその他の属性) を管理する必要がないようにするために、すべてのプロパティの検証属性を 1 つのクラスに記述し、それを 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.

Google 翻訳:

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、例外がスローされます。これを防ぐ方法はありますか?

4

1 に答える 1