繁体   English   中英

使用实体框架在自己的 class 库中创建 DAL

[英]Creating a DAL within its own class library using Entity Framework

更新:这不是 web 应用程序; 它是一个服务器服务,有很多以不同方式访问数据库的 DLL。 我需要一种方法来拥有一个可以提供对数据库的访问的 singleton 实体框架 DLL。

我正在尝试在我的项目中使用实体框架 6 设置 DAL DLL object。 我想调用单个 object,而不是在所有需要它的对象中设置 model。 这样我就可以在一个地方更新数据 model 并且我的所有库也将被更新。

因此,在我的项目中,我创建了一个 .NET 框架项目并链接到数据库以创建 model(DB 优先)。 这样该项目就可以看到 model 了。

然后,我可以在解决方案中的其他项目之一中链接到 DLL 对象的 model,方法是创建对项目的引用并链接到创建的实体,如下所示:

ModelEntities db = new ModelEntities();

我可以看到所有创建的方法和对象。 但是当我运行一个非常简单的查询时,我似乎无法访问数据库:

var dbRecord = (from record in db.UserKey).FirstOrDefault();

我可以在实体 model class 中创建一个测试,然后运行上面的查询没有问题。 当我检查 db object 时,它看起来已经初始化了。

Then thinking about it, I'm not sure the entity model is logged into the SQL Server using the outside object and that theory seems verified when I step through the code, the db object in that case has a bunch of exceptions on it even before运行查询。

我什至不确定我是否首先要解决这个问题。 这绝对是一种可能性。 但在我是对的情况下,如何在调用查询之前初始化远程实体 class 中的数据库连接?

当您在 ClassLibrary 中创建 EntityFramework edmx 时,它会在该项目中创建一个配置文件。 您的应用程序主 webconfig 将没有来自您的 class 库的配置信息,并且将无法工作。

解决方案是将连接字符串配置项复制到应用程序项目的 web 配置以及 EntityFramework 配置标记中。

连接字符串:

  <connectionStrings>
    <add name="ADatabase" connectionString="" providerName="System.Data.EntityClient" />
  </connectionStrings>

实体框架标签

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM