简体   繁体   English

调用使用实体框架的DAL

[英]Calling DAL that uses Entity Framework

I have a Web API application that is calling a DAL library. 我有一个Web API应用程序正在调用DAL库。 The DAL library interacts with a SQL database using Entity Framework. DAL库使用实体框架与SQL数据库进行交互。 Now, I need to set the connection string to the database in the Web API project. 现在,我需要在Web API项目中设置数据库的连接字符串。 This requires me to install EF in the Web API project as well. 这也需要我在Web API项目中安装EF。 Is there any way I can set the connection string in the Web API project without having to install EF? 有什么方法可以在Web API项目中设置连接字符串而无需安装EF?

You can wrap the DbContext, this way, the DAL project is not exposing any EF related components. 您可以包装DbContext,这样,DAL项目就不会公开任何与EF相关的组件。 By doing this you don't have to install EF into every project you reference the DAL project in. 这样,您不必在引用DAL项目的每个项目中都安装EF。

public class DataContextWrapper : IDisposable {
    public DataContextWrapper() {
        DataContext = new DataContext();
    }

    internal DataContext DataContext { get; private set; }

    public void Dispose() {
        DataContext.Dispose();
    }
}

As long as your repositories etc are also in the DAL project and they do not return database entities but models, you will be fine. 只要您的存储库等也位于DAL项目中,并且它们不返回数据库实体而是模型,就可以了。

I am using the same connection string used by EF in my web api project. 我在我的Web api项目中使用了EF使用的相同连接字符串。 I referenced the EntityFramework.SqlServer.dll in the web api project. 我在网络api项目中引用了EntityFramework.SqlServer.dll。 And now, it works. 现在,它可以工作了。

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

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