Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't use required attribute in the asp.net vnext class library

Update: Of course I tried to add using System.ComponentModel.DataAnnotations. It doesn't work.

Problem: I can't use Required attribute in asp.net vnext class library project.

Case:
1. Add asp.net vnext class library project with default settings.
2. Create class Human with string property Name.
3. Add Required attribute to the Name.
4. Get compilation error:

Error   CS0246  The type or namespace name 'Required' could not be found (are you missing a using directive or an assembly reference?)  

Below is my project.json:

{
    "version": "1.0.0-*",
    "dependencies": {
        "System.ComponentModel.Annotations": ""
    },
    "frameworks": {
        "aspnet50": {
        },
        "aspnetcore50": {
            "dependencies": {
                "System.Runtime": ""
            }
        }
    }
}

Also I can use DataAnnotations in asp.net vnext, but not in vnext class library. Why?

like image 700
Mark Twain Avatar asked Feb 23 '15 19:02

Mark Twain


1 Answers

The vNext web project has a dependency on Microsoft.AspNet.Mvc. This pulls in a big tree of dependencies, the data annotations are under the package Microsoft.DataAnnotations

Add a dependency for Microsoft.DataAnnotations to use the data contract attributes.

In your project.json file change

"dependencies": {
    "System.ComponentModel.Annotations": ""
},

to

"dependencies": {
     "Microsoft.DataAnnotations":  "1.0.0-beta1"
},

Replace 1.0.0-beta1 with whatever the current version number is. Visual studio will auto-complete it for you.


Why does Microsoft.DataAnnotations work and not System.ComponentModel.Annotations?

From a little investigation System.ComponentModel.Annotations contains two targets

  • aspnetcore50\System.ComponentModel.Annotations.dll
  • contract\System.ComponentModel.Annotations.dll

The aspnetcore50 assembly is for the new Core CLR. It's contains the Required attribute and works for the Core CLR.

The contract assembly contains all the types but the methods are empty. It's like a dummy dependency that has to be fulfilled by the framework. This dummy assembly is used on .NET 4.5 which is why your project targeting both .NET 4.5 and the Core CLR can't find the Required attribute.

On the other hand the Microsoft.DataAnnotations package depends on System.ComponentModel.Annotations but also references the framework assembly System.ComponentModel.DataAnnotations which actually provides the types when you run on .NET 4.5

I found this post interesting. It explains what these contract assemblies are towards the end of the post. http://alxandr.me/2014/07/20/the-problems-with-portable-class-libraries-and-the-road-to-solving-them/

like image 79
Jared Kells Avatar answered Sep 30 '22 06:09

Jared Kells