Skip to content

MetadataTypeAttribute doesn't influence DataAnnotations validation result #46678

Closed

Description

@RichardBr

Update by @SteveSandersonMS: please see the comment #46678 (comment) for a description of the underlying issue/question.

Please ignore the parts of this thread that are specific to Blazor. That's just how the issue was originally reported, but it looks like the underlying concern is about DataAnnotations itself.


Describe the bug

When I use the MetadataType attribute (from System.ComponentModel.DataAnnotations) on the class for the purpose of validation I get the following error in the console window
WASM: System.TypeLoadException: Could not resolve type with token 01000027 from typeref (expected class 'System.ComponentModel.DataAnnotations.MetadataTypeAttribute' in assembly 'System.ComponentModel.Annotations, Version=4.3.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')

Greater details of the error are shown in this file...[console screenshot - validation error](https://user-images.githubusercontent.com/5938313/79199691-42595400-7e2d-11ea-95bc-3c2248d8b60e.png

Please note my sample application does works when I put all validation attributes into main the class.

For clarity:
This approach works...

public partial class PersonViewModel
{
    [Required(ErrorMessage = "First name is required.")]
    public string Fname { get; set; }
}

This approach fails...

public partial class PersonViewModel
{
    public string Fname { get; set; }
}

[MetadataType(typeof(PersonViewModelMetaData))]
public partial class PersonViewModel
{
}

public class PersonViewModelMetaData
{
    (ErrorMessage = "First name is required.")]
    public string Fname { get; set; }
}

To Reproduce

Please run the attached sample blazor application. To see the error please click the navigation link labelled "validation - failure". On the page, just simply press the submit button to see the error.
BlazorAppValidation.zip

Further technical details

  • Include the output of dotnet --info
.NET Core SDK (reflecting any global.json):
 Version:   3.1.300-preview-015048
 Commit:    13f19b4682

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.18363
 OS Platform: Windows
 RID:         win10-x64
 Base Path:   C:\Program Files\dotnet\sdk\3.1.300-preview-015048\

Host (useful for support):
  Version: 3.1.3
  Commit:  4a9f85e9f8

.NET Core SDKs installed:
  3.1.101 [C:\Program Files\dotnet\sdk]
  3.1.201 [C:\Program Files\dotnet\sdk]
  3.1.300-preview-015048 [C:\Program Files\dotnet\sdk]

.NET Core runtimes installed:
  Microsoft.AspNetCore.All 2.1.16 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.All]
  Microsoft.AspNetCore.App 2.1.16 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.2 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.AspNetCore.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.AspNetCore.App]
  Microsoft.NETCore.App 2.1.16 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.2 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.NETCore.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.NETCore.App]
  Microsoft.WindowsDesktop.App 3.1.1 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
  Microsoft.WindowsDesktop.App 3.1.2 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]
  Microsoft.WindowsDesktop.App 3.1.3 [C:\Program Files\dotnet\shared\Microsoft.WindowsDesktop.App]

To install additional .NET Core runtimes or SDKs:
  https://aka.ms/dotnet-download

Activity

  1. javiercn commented on Apr 14, 2020

    @javiercn
    Member

    @RichardBr thanks for contacting us.

    This is not a feature that we currently support AFAIK.

    /cc: @SteveSandersonMS @pranavkm

  2. nssidhu commented on Apr 23, 2020

    @nssidhu

    This is much needed as in case of scaff folding it just delete and recreates the class again, we would have to re-write everything again. please consider to implement it, need for real life project

  3. mkArtakMSFT commented on Apr 24, 2020

    @mkArtakMSFT

    We've moved this issue to the Backlog milestone. This means that it is not going to happen for the coming release. We will reassess the backlog following the current release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources.

  4. wmgdev commented on Jun 10, 2020

    @wmgdev

    Agree, It would be really nice if MetadataType worked.
    It would allow us to add data annotations for validation to Models generated using Scaffold-DbContext

  5. MattSturtivant commented on Jul 7, 2020

    @MattSturtivant

    Just wanted to add a +1 for this - while we can setup a task to mix-in our data annotations after scaffolding for now, I feel this is a regression from MVC.

  6. Gambero81 commented on Aug 31, 2020

    @Gambero81

    this is a must have feature, especially in projects with automatic class generations like Entity Framework, to allow adding additional validation or business rules.

    Hope it will be implemented as soon as possible

  7. IanKemp commented on Sep 7, 2020

    @IanKemp

    We've moved this issue to the Backlog milestone. This means that it is not going to happen for the coming release. We will reassess the backlog following the current release and consider this item at that time. However, keep in mind that there are many other high priority features with which it will be competing for resources.

    Those "high-priority" features won't matter if big corporates decline to use Blazor because its model-binding support sucks.

  8. navidzehi commented on Oct 10, 2020

    @navidzehi

    This is really an important issue. One of the main advantages of Blazor versus frameworks like Angular is the rapid development due to capability of reusing the 'server code' for validation or generation of models in the client. @mkArtakMSFT

  9. SteveSandersonMS commented on Dec 17, 2020

    @SteveSandersonMS
    Member

    I've just been checking this, and I don't think this issue is Blazor-specific. I think it's a more general point that System.ComponentModel.DataAnnotations.MetadataTypeAttribute doesn't actually do anything to influence the DataAnnotations validation result.

    To repro my findings, create a new .NET Core Console Application (so that's neither Blazor nor WebAssembly), containing:

        [MetadataType(typeof(PersonMetadata))]
        public class Person
        {
            public string Name { get; set; }
        }
    
        public class PersonMetadata
        {
            [Required]
            public string Name { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                // Some people say you should do this, but it doesn't seem to make any difference
                TypeDescriptor.AddProviderTransparent(
                    new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Person), typeof(PersonMetadata)),
                    typeof(Person));
    
                var person = new Person();
                var results = new List<ValidationResult>();
                var isValid = Validator.TryValidateObject(person, new ValidationContext(person), results);
                Console.WriteLine($"isValid: {isValid}");
            }
        }

    I would have expected this to say isValid: False but actually it says isValid: True. I can only get it to respect the [Required] attribute by putting it directly onto Person, not PersonMetadata. Also notice that this has nothing to do with partial classes (I'm not using them above).

    @pranavkm Do we have any contacts who work on DataAnnotations? This seems like a weirdness that a lot of people have complained about all over StackOverflow etc. I can't tell whether it used to work in the past (e.g. on .NET Framework) since some people say it does if you use TypeDescriptor.AddProviderTransparent, but it certainly doesn't appear to work now.

  10. Gambero81 commented on Jan 5, 2021

    @Gambero81

    news on this issue?

  11. DiegoVenancioVieira commented on Jan 5, 2021

    @DiegoVenancioVieira

    news on this issue?

    Nothing, there are many other priorities. This is just one more in the backlog list. Waiting too

  12. added
    untriaged
    on Jan 7, 2021
  13. 27 remaining items

  14. eerhardt commented on May 28, 2021

    @eerhardt
    Member

    I'm not sure what the rules are on sharing modified versions of the DotNet files. @eerhardt can you advise?

    Until the change is merged into main, my recommendation would be to pull the change locally and build the file locally.

  15. rahul7720 commented on Jun 19, 2021

    @rahul7720

    Hi Guys,

    Any updates on this?

  16. Xaeco commented on Jul 8, 2021

    @Xaeco
    Contributor

    Still waiting on my pull request to be reviewed. No further progress.

  17. added this to the 6.0.0 milestone on Jul 13, 2021
  18. removed
    untriaged
    on Jul 13, 2021
  19. Xaeco commented on Jul 25, 2021

    @Xaeco
    Contributor

    Update. Option 1 has been approved. Not sure if it will land in a .NET 6 preview or the final release.

  20. Xaeco commented on Jul 25, 2021

    @Xaeco
    Contributor

    @ajcvickers any chance this fix could be back-ported to .NET 5?

    If so what is the process?

  21. rahul7720 commented on Jul 25, 2021

    @rahul7720

    @Xaeco Any chance if you can build an unofficial NuGet package / Dll and release it for testing purposes?

  22. added
    in-pr
    on Jul 27, 2021
  23. bricelam commented on Jul 27, 2021

    @bricelam
    Contributor

    See also (and upvote) dotnet/efcore#14544

  24. ghost closed this as completedin #51772on Jul 28, 2021
  25. ghost removed
    in-pr
    on Jul 28, 2021
  26. ghost locked as resolved and limited conversation to collaborators on Aug 27, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions