AlexandreG
AlexandreG

Reputation: 1683

type or namespace name 'DataAnnotations' does not exist in the namespace 'System.ComponentModel'

While I added the Nuget packages System.ComponentModel.AnnotationsI am getting the error

type or namespace name 'DataAnnotations' does not exist in the namespace 'System.ComponentModel'

What happened is that I openend an old ASP.NET Core 1.0 project from a book sample and VS17 upgraded it. Then off course I got a lot of warnings from the VS17 in the NuGet dependencies. So I converted the project to Core 2.1 and updated all NuGet dependencies.

But now it complains about the attributes.

Any idea ?

enter image description here

Upvotes: 4

Views: 6207

Answers (4)

lsaudon
lsaudon

Reputation: 1468

Add this package System.ComponentModel.Annotations

Upvotes: 1

AlexandreG
AlexandreG

Reputation: 1683

Ok, so a bypass to this issue was to run in the command of the project root dotnet restore after VisualStudio did his conversion thing.

This solved the issue without having to convert to .NET core 2.0 or higher.

Upvotes: 1

Leo Liu
Leo Liu

Reputation: 76770

type or namespace name 'DataAnnotations' does not exist in the namespace 'System.ComponentModel'

First, you can notice that the Description about the package System.ComponentModel.Annotations:

enter image description here

There is no direct namespace System.ComponentModel.Annotations we can use. So, although we install the System.ComponentModel.Annotations Nuget package and then use the System.ComponentModel.DataAnnotations namespace. Clarification for those like me that got hung up a different namespace for longer.

So we do not need the first namespace statement.

For the second, just like turao8 said, the Microsoft.AspNetCore.App including the it's own version of data annotations, we do not need add it again with nuget package.

I have created a test sample with out any other nuget package, it works fine:

enter image description here

To resolve this issue, you can create a new .net core 2.1 project, then copy the code to the new project, then add the references as needed, after all, the old .net core 1.0 and 2.1 still have a lot of differences.

Hope this helps.

Upvotes: 3

marcusturewicz
marcusturewicz

Reputation: 2494

Updating from 1.0 to 2.x is not as simple as updating the nuget packages. You may need to change your code since there were breaking changes in the framework. As far as I can tell, you will need to upgrade the app from 1.0->2.0. Then you will need to upgrade from 2.0->2.1.

Once you do that, it should automatically handle your data annotations issue, because ASP.NET Core has it's own version of data annotations which is part of Microsoft.AspNetCore.App (which you will include as part of the second migration), as you can see in the dependecy list below:

enter image description here

Upvotes: 0

Related Questions