Entity Framework in Class Library without outside references

asp.net-web-api c# entity-framework-6


I'm trying to figure out how to add Entity Framework 6 into a separate class library without having the web.config inside the client project knowing anything about DB connections of its helper class libraries. The reason for that is that a single client will be able to talk to different components, which will all have wildly different functionalities and DBs. Because of this I want to expose a basic set of common functions that the Class Libraries will expose without the Client application having to care about how they get that information.

Surely this must be possible. Am I mistaken?

This is the planned structure:

  • Web API Project
    • Class Library 1 (DB1)
    • Class Library 2 (DB2)
    • Class Library 3 (might or might not contain DB)

I have tried moving the EF references to a separate project but cannot seem to be able to make a connection to the DB unless the client project has the connection string, which is not ideal...

9/10/2016 7:07:56 AM

Popular Answer

From question what I understand is that your Class Library projects have their own DB connections which client will NOT know.

You want your Class Libraries to some how read these DB connection information from some place, and that some place should NOT be client's web.config file.

If my above understanding is correct, then you can have a separate config file, for example class1project.xml, and your library will always read this xml file for the connection information.

Your next question might be, how your client will initialize the DBContext class from our class library. Since your context class is still looking for a particular connection string in web.config file.

For this you can have your context class' constructor set as internal so that your client cannot call it on its own. Then can have some other static class in your project with static method like CreateContext and this method will initialize the context class by passing appropriate connection information which it will read from class1project.xml file.

9/10/2016 9:59:20 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow