简体   繁体   中英

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. 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.

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?

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.

Sharing classes among Context is not recommended, especially if they belong to different databases. 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. (But this is not multiple DB in one application, that's multiple application on one DB).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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