-
Notifications
You must be signed in to change notification settings - Fork 4.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
MetadataTypeAttribute doesn't influence DataAnnotations validation result #46678
Comments
@RichardBr thanks for contacting us. This is not a feature that we currently support AFAIK. |
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 |
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. |
Agree, It would be really nice if MetadataType worked. |
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. |
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 |
Those "high-priority" features won't matter if big corporates decline to use Blazor because its model-binding support sucks. |
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 |
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 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 @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 |
news on this issue? |
Nothing, there are many other priorities. This is just one more in the backlog list. Waiting too |
Tagging subscribers to this area: @ajcvickers Issue DetailsDescribe the bugWhen 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 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 fails...
To ReproducePlease 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. Further technical details
|
Any news on this issue? Any alternatives as a short term? |
No |
Did major work migrating my project to Blazor and didn't see this one coming. |
@Xaeco Maybe this can help you for now C# new source generator |
@navidzehi Can you tell us HOW? Which part of video ? |
@DiegoVenancioVieira well,I haven't try it myself but I think it's possible to do the following.
then you may also have the following classes :
Now in a way that is mentioned in the video you have generate the following model and instead of using the Person model you use the Person_Generated(with your own naming convensions) in your whole application :
you also need to add the following Partial class manually (or maybe you can manage to generate it too for an existing project):
another option is also to include the FullName in the first Person_Generated.cs partial file. |
Thanks for your time. What I'm attempting to do is decorate classes that have been auto generated by .proto file compilation so that the DataAnnotationsValidator in Blazor has something to work with. As per your example I'd need to write a source generator to make a new set of classes based on the auto-generated ones and weave in the data annotations. |
I am also very interested in this feature. We would like to decorate classes generated from .proto files as well and use them with the I dug into the code a bit and it looks like the .NET 5 version of |
I'm going to have a go at fixing it |
This seems to be generally the problem with decorating any autogenerated class with attributes. I am experiencing a similar issue with trying to add XmlElement and XmlAttribute to classes generated from a proto file that need to be deserialized from an xml payload. The MetadataType attribute seems to have no effect whatsoever. I also tried to use MetadataType on a simple class and it seems to be just completely ignored, so it's not something to do with autogenerated files or protobuf, it just seems to not work at all even in the simplest scenario. (I am using .net standard 2.1 and System.ComponentModel.Annotations nuGet version 5.0.0) |
I created a small test project to investigate the DataAnnotations behaviour. Some findings:
TypeDescriptor.AddProviderTransparent(
new AssociatedMetadataTypeTypeDescriptionProvider(typeof(Person), typeof(PersonMetadata)),
typeof(Person)); You don't need to use [MetadataType(typeof(PersonMetadata))] As it makes no difference to .Net Framework 4.5+ The Core project doesn't produce the expected results. I went through the .Net Core 5 code, specifically through the System.ComponentModel.Annotations solution. I couldn't find any direct references to MetadataTypeAttribute or AssociatedMetadataType in the context of the TryValidateObject code. I will keep digging. |
So I have coded two working solutions. Solution 1
Solution 2
Both solutions require adding a couple of methods to the System.ComponentModel.Annotations.Validator class. This resides in .Net Standard 2.1. I'm guessing any fixes would come out in a .NET 6 beta and not to any older versions? So I'm hoping for some assistance here on which implementation to use. Like to hear everyone's vote? |
I prefer Solution 2 , Its the same as old silverlight WCF RIA services used. |
Solution 2 for sure!. |
Thank you to all who have commented. |
@SteveSandersonMS I have two working solutions for this issue. Solution 1. Is to replace two functions with their DN4.8 equivalents. They use TypeDescriptor, which as far as I can tell, is being avoided. Solution 2. I wrote functions that work but when I do a full build I get an IL Linker error which I can't suppress and I'm not sure I should. I'd appreciate talking to someone re the best way forward. |
Thanks for the effort guys. |
FYI @ajcvickers |
The listed owners of the
@Xaeco - can you try rebasing your change on the latest main? I merged #49901 last week, which resolved the existing ILLink warnings in that library. If you are still seeing warnings, can you send them to me, along with your change? I can assist in getting them resolved. |
Excellent. I will give it a go and let you know. Thank you> The listed owners of the
|
I've had a PR in for the fix for 29 days now but haven't had anyone look at it yet. Not sure if I've missed part of the process or everyone is really busy and this is too low priority. Any assistance would be appreciated. Thanks. |
Hi all! |
@Xaeco Thanks for your contribution. I'm waiting for this fix for a long time. Will this be released under DotNet 5.0 or DotNet 6.x preview? |
Hi again. |
Hi. At the moment its in the DotNet 6.x preview codebase. Hopefully it gets approved soon. Meanwhile I'll look into the process to backport it to DotNet 5.0 if that's at all possible. Currently I am testing my fix locally by incorporating the updated DotNet classes (with a few references changed) into my Blazor project and using a custom validator. The custom validator is required because Blazor's validator is using DotNet 6 Preview internally and that doesn't have my code in it. This works for DotNet 5 & 6. 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 |
Hi Guys, Any updates on this? |
Still waiting on my pull request to be reviewed. No further progress. |
Update. Option 1 has been approved. Not sure if it will land in a .NET 6 preview or the final release. |
@ajcvickers any chance this fix could be back-ported to .NET 5? If so what is the process? |
@Xaeco Any chance if you can build an unofficial NuGet package / Dll and release it for testing purposes? |
See also (and upvote) dotnet/efcore#14544 |
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...
This approach fails...
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
dotnet --info
The text was updated successfully, but these errors were encountered: