简体   繁体   English

如何在实体框架中的多个数据库之间共享类?

[英]How to share classes between multiple databases in Entity Framework?

We have two different applications (project 1, project 2) that will be using two different databases for different purposes, but there are a few tables/classes from DB1 that it would make sense for DB2 to use.我们有两个不同的应用程序(项目 1、项目 2),它们将出于不同目的使用两个不同的数据库,但是 DB1 中的一些表/类对于 DB2 使用是有意义的。 We are using code-first Entity Framework to create both databases.我们使用代码优先的实体框架来创建这两个数据库。 The current approach is to just have similar classes in DB2, and have project 1 make the translation from DB1 objects to DB2 objects before providing the data to project 2. I'm wondering if I can make a design change to eliminate the translation and repetitive classes, and just have both projects use common classes.当前的方法是在 DB2 中仅具有类似的类,并让项目 1 将 DB1 对象转换为 DB2 对象,然后再将数据提供给项目 2。我想知道是否可以进行设计更改以消除转换和重复类,只是让两个项目都使用公共类。

What I'm wondering is if there is a way to put the 3 or 4 classes we want to share between the projects into some library that can be referenced in both projects and included in their DB?我想知道是否有办法将我们想要在项目之间共享的 3 个或 4 个类放入某个库中,该库可以在两个项目中引用并包含在它们的数据库中?

Current design looks like this:当前的设计如下所示:

DB1 project:  
User   
Task  
many different tables  

DB2 project:  
User   
Task  
many different tables 

While I'm imagining something like this:虽然我在想象这样的事情:

Class Library project:  
User  
Task

DB1 project:  
Reference to Class Library      
many different tables  

DB2 project:  
Reference to Class Library  
many different tables 

Is there a way to make this work with two Entity Framework databases?有没有办法让这两个实体框架数据库一起工作?

EF just requires one DbContext per C#project, this is to address migration etc. You can have several projects in your application. EF 只需要每个 C#project 一个 DbContext,这是为了解决迁移等问题。您的应用程序中可以有多个项目。

Sharing classes among Context is not recommended, especially if they belong to different databases.不建议在 Context 之间共享类,尤其是当它们属于不同的数据库时。 From having an entity in your code, you should always be able to tell, what DB it belongs to.通过在您的代码中拥有一个实体,您应该始终能够知道它属于哪个数据库。

But you also mention "different application" that's another Scenario, like having a front-end and backend application of the same database?但是您还提到“不同的应用程序”,这是另一个场景,例如拥有同一个数据库的前端和后端应用程序? They can share the same C# projects with Entity classes.他们可以与实体类共享相同的 C# 项目。 (But this is not multiple DB in one application, that's multiple application on one DB). (但这不是一个应用程序中的多个数据库,而是一个数据库上的多个应用程序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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