命名空间 'System.ComponentModel' 中不存在类型或命名空间名称 'DataAnnotations'

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

当我添加 Nuget 包时 System.ComponentModel.Annotations我收到错误

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

发生的事情是我从一本书示例中打开了一个旧的 ASP.NET Core 1.0 项目,然后 VS17 对其进行了升级。然后当然我在 NuGet 依赖项中收到了很多来自 VS17 的警告。所以我将项目转换为 Core 2.1 并更新了所有 NuGet 依赖项。

但现在它抱怨属性。

有什么想法吗?

从 1.0 更新到 2.x 并不像更新 nuget 包那么简单。您可能需要更改代码,因为框架中发生了重大更改。据我所知,您需要升级应用程序 from 1.0->2.0. Then you will need to upgrade from 2.0->2.1

一旦你这样做,它应该会自动处理你的数据注释问题,因为 ASP.NET Core 有它自己的 version of data annotations which is part of Microsoft.AspNetCore.App(你将把它作为第二次迁移的一部分),你可以请参阅下面的依赖列表:

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

首先,您可以注意到关于包的描述 System.ComponentModel.Annotations:

没有我们可以使用的直接命名空间System.ComponentModel.Annotations。所以,尽管我们安装了 System.ComponentModel.Annotations Nuget 包,然后使用 System.ComponentModel.DataAnnotations 命名空间。澄清那些像我一样长时间挂断不同命名空间的人。

所以我们不需要第一个命名空间语句。

第二种,就像turao8说的,Microsoft.AspNetCore.App包括自己版本的data annotations,不需要用nuget包再添加。

我创建了一个没有任何其他 nuget 包的测试样本,它工作正常:

解决这个问题,可以新建一个.net core 2.1项目,然后把代码复制到新项目中,然后根据需要添加引用,毕竟老的.net core 1.02.1还是有很大的不同。

希望这对您有所帮助。

好的,所以绕过这个问题的方法是在 VisualStudio 完成转换之后 运行 在项目根 dotnet restore 的命令中。

这解决了问题,而无需转换为 .NET core 2.0 或更高版本。

添加这个包System.ComponentModel.Annotationse