entity-framework - 我们是否应该将 Entity Framework dll 添加到所有层

标签 entity-framework ef-code-first entity-framework-6

我首先使用 EF 代码编写测试应用程序。我在不同的层之间分发了代码。我以为我只需要将 Entity Framework 包安装到数据访问层,但我最终将包(添加 dll)安装到所有层,即 UI、BLL、模型、DAL。这是可以的,还是我做错了什么。下面是示例代码,让您了解我正在尝试做什么

模型层

该层是所有其他层/项目的引用

namespace Model
{
   Public class Sample
   {
      [ForeignKey("Sample2Id")]
      ...

   }
} 

在这一层我不得不使用 Entity Framework dll,因为像 [ForeignKey.. 这样的数据注释

DAL
namespace DAL
{
   public class SampleContext:DbContext
   {
      ...
   }
}

在 DAL 中,我只有上下文类和迁移

BLL
namespace BLL
{
   public class SampleBLL
   {
       public List<Sample> GetAll()
       {
          retrn new SampleContext().Samples().ToList()
       }
   }
}

如果我为 BLL 卸载 EF,则会出现以下错误
System.Data.Entity.DbContext 类型是在未引用的程序集中定义的。

用户界面
namespace UI
{
   public class UIHelper
   {
      public List<Sample> GetSamples()
      {
         return new SampleBLL().GetAll();
      }

   }
}

如果我从 UI 卸载 EF 包,我会收到以下错误

The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application

最佳答案

我创建了一个示例项目,它与您当前的设置非常相似,减去模型层/DAL 分离。

我有三个项目, DAL (其中包含对 EntityFramework.dllEntityFramework.SqlServer.dll 的引用)、 BLL 它只是调用了 中的一个方法DAL ,以及 用户界面 这只是调用 BLL 方法。

我不得不添加 <configSections> , <entityFramework> ,以及 <connectionStrings> app.config 的部分的 DAL 用户界面 app.config .

当我第一次运行代码时,我遇到了与您遇到的相同的错误。所以我查看了我的 的调试文件夹用户界面 项目并注意到 EntityFramework.dll由于 被复制到文件夹中DAL 对它的依赖。我还注意到 EntityFramework.SqlServer.dll尽管 没有被复制到调试文件夹中DAL 对它也有依赖性。

我复制了 EntityFramework.SqlServer.dll进入 UI 项目的调试文件夹,然后重新运行项目,Viola!我的代码按预期运行。

看起来这里的问题是一个 dll 没有像预期的那样被复制到 UI 项目调试文件夹中。

关于entity-framework - 我们是否应该将 Entity Framework dll 添加到所有层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31995835/

相关文章:

sql-server - update-database -force 命令未更新 Entity Framework 代码中的基础 -first

entity-framework - 自引用多对多关系EF代码优先

c# - Entity Framework 6 内存使用量达到 2GB

entity-framework - EF6 Beta1 - db.Database.CreateIfNotExists();启用迁移后不再创建数据库

.net - 如何使用 Entity Framework 6.1 正确标记标识列?

asp.net-mvc - 在 EntityFramework 和 Moq 中模拟模型集合

c# - 无法访问已处置的对象。交易

c# - 使用 Entity Framework 添加具有读/写操作和 View 的 Controller 会导致警告

c# - EF Code First : Duplicate foreign keys (one from name convention, 来自导航属性)

c# - Entity Framework 4.3 代码优先数据库命名