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

梦想与她 提交于 2019-12-12 08:20:05

问题


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();
 }

回答1:


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:

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.




回答2:


I would create a separate data access project. It is good practice to separate your data layer out anyhow. Depending on the nature of the project and how you want to test it, you may want to take a look at something like the repository pattern (though there is debate about its value with EF).

http://msdn.microsoft.com/en-us/library/ff649690.aspx



来源:https://stackoverflow.com/questions/17118775/i-have-three-projects-that-share-the-same-db-whats-the-best-way-to-use-ef-acros

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!