简体   繁体   中英

Calling DAL that uses Entity Framework

I have a Web API application that is calling a DAL library. The DAL library interacts with a SQL database using Entity Framework. Now, I need to set the connection string to the database in the Web API project. This requires me to install EF in the Web API project as well. Is there any way I can set the connection string in the Web API project without having to install EF?

You can wrap the DbContext, this way, the DAL project is not exposing any EF related components. By doing this you don't have to install EF into every project you reference the DAL project in.

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.

I am using the same connection string used by EF in my web api project. I referenced the EntityFramework.SqlServer.dll in the web api project. And now, it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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