【问题标题】:C# The type 'ForeignKeyAttribute' exists in both EntityFramework and System.ComponentModel.DataAnnotationsC# EntityFramework 和 System.ComponentModel.DataAnnotations 中都存在“ForeignKeyAttribute”类型
【发布时间】:2018-02-01 01:06:54
【问题描述】:

我将项目从 .net 4.0 升级到 .net 4.5.1。

我将 EntityFramework 从 4.3.1 升级到 6.1.3。

但 EntityFramework 基于 .net 4.0 (\packages\EntityFramework.6.1.3\lib\net40\EntityFramework),因为另一个依赖项目运行 .net 4.0。

当我构建时,我得到了这个错误:

“EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”和“System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35”中都存在“ForeignKeyAttribute”类型

提前致谢。

【问题讨论】:

  • 您可能需要从代码中删除 using System.ComponentModel.DataAnnotations;
  • 嗨伊万。我试过了,但我得到了这个错误:找不到类型或命名空间名称“KeyAttribute”(您是否缺少 using 指令或程序集引用?)
  • 对不起,忽略我之前的评论。实际上,在我的 EF6.1.3 测试项目中,我有 using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; 并且两个属性都来自 Assembly System.ComponentModel.DataAnnotations, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 看起来您的场景中的 EntityFramework 程序集有问题,不知道如何解决。祝你好运。
  • 感谢您的建议。但是我升级了依赖的项目:)

标签: c# entity-framework-6 .net-framework-version


【解决方案1】:

仅仅从项目中删除DataAnnotations 4.0.0 引用可能还不够。即使您的 packages.config 中对 Entity Framework 的引用可能会更新为正确的版本,但 targetFramework 值仍可能会影响代码的编译方式。

我正在升级最初针对 Framework 4.0 的 ASP.NET MVC 3 应用程序。我首先升级了 NuGet 包,其中包括 EntityFramework 4.x。后来我知道我需要一个更新的 .NET Framework 版本。在选择将每个项目升级到 .NET Framework 4.7.1 后,我开始遇到CS0433 错误。在升级 NuGet 包之后升级框架版本 似乎使 targetFramework 保持不变。

为了解决这个问题,我手动将每个项目的 packages.config 文件更新为新的 targetFramework 值,从 net40net471。为了使这些更新的值生效,我从 NuGet 包管理器控制台运行了Update-Package -reinstall。现在使用“EntityFramework 6.2.0”中包含的DataAnnotations,而不是 4.0.0 中的外部可用。

【讨论】:

  • Update-Package -reinstall 为我工作。谢谢
【解决方案2】:

Entity Framework 6 包含来自 System.ComponentModel.DataAnnotations 和 System.ComponentModel.DataAnnotations.Schema 命名空间的大量内容。 据我所知,解决方法是删除项目 Reference 到 System.ComponentModel.DataAnnotations

【讨论】:

  • 我试过了,但如果我删除 DLL System.ComponentModel.DataAnnotations 的引用,我会收到错误 KeyAttribute class not found 因为不在 EntityFramework 程序集中。关于如何解决这个问题的任何想法?
  • @EinerSantana 这是个好问题。让我检查一下。 EF 使用 [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] 表示主键。嗯。 EF 6.2 我只看到“IndexAttribute”,其他都没有。他们又改变了我的事情吗?
猜你喜欢
  • 1970-01-01
  • 2011-03-21
  • 2019-03-03
  • 2022-01-16
  • 2020-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多