我有三个项目共享相同的数据库,什么是最好的方法来使用所有的EF? [英] I have three projects that share the same DB, whats the best way to use EF across all?

查看:123
本文介绍了我有三个项目共享相同的数据库,什么是最好的方法来使用所有的EF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个项目(WCF项目,而不是客户端),我有一个数据库,现在我将如何使用EF?我应该做一个第四个项目,它将具有数据库环境和实体,然后在所有三个项目中添加一个引用它?或者我应该为每个项目分别设置一个上下文,然后添加每个项目需要的表格?一些桌子真的在使用无处不在。那么这是最好的解决方案?



另一个问题:我应该在单独的项目中公开EF数据库上下文,以便其他项目可以访问它?如下所示:

  MySeparateProject myPr = new MySeparateProject(); 
使用(var db = new myPr.DBContext())
{
//做实体
db.SaveChanges();
}


解决方案

我认为最干净的事情do是创建一个数据访问项目(类库),它只包含您的模型和数据库上下文,并引用所有其他项目。有些人会说,你应该只用一个模型来创建一个类库,然后再创建一个具有DbContext的库,然后使用这个库。 ...我觉得这对大多数项目来说都是过分的。将模型和上下文放在一起只是使得在数据访问时保持所有依赖项目始终保持同步的状态非常简单。



这是一个典型的项目结构我:





这里, Squelch.Data 包含我所有的模型和数据库上下文, Squelch.Core 包含核心业务逻辑,而我的两个应用程序( Squelch.Portal 广告 CdrImport ),以及各种测试用例,都引用了这些基类库。


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

解决方案

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.

这篇关于我有三个项目共享相同的数据库,什么是最好的方法来使用所有的EF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆