I have three projects that share the same DB, whats the best way to use EF across all?

user915331 picture user915331 · Jun 15, 2013 · Viewed 11k times · Source

I have three projects (WCF projects, not clients), I have one database for all, now how will I use EF with this? should I make a fourth project which will have the db context and the entities and then add a reference to it in all three projects? or should I just have a separate context for each project and just add the tables i need for each project? some of the table are really used everywhere. so what's the best solution for this?

Another question: should I expose the EF db context in the separate project so other projects can access it? something like:

 MySeparateProject myPr = new MySeparateProject();
 using (var db = new myPr.DBContext())
 {
     // do stuff with entities
     db.SaveChanges();
 }

Answer

Myk Willis picture Myk Willis · Jun 15, 2013

I think the cleanest thing to do is create a data access project (class library) that contains just your models and db context, and reference that from all of your other projects.

Some people will say that you should make one class library with just the models, and then have yet another that has the DbContext, and the have repository classes, and then.... I feel this is overkill for the majority of projects. Having the models and context in one place just makes it really easy to keep all the dependent projects consistently in sync when it comes to data access.

Here's a typical project structure for me:

enter image description here

Here, Squelch.Data contains all of my models and db contexts, Squelch.Core contains core business logic, and my two "applications" (Squelch.Portal ad CdrImport), and the various test cases, all reference these base class libraries.