0

Is there a way to use Entity Framework with more than one database? Even further make relationship between them tables? I have multiple projects which use each other tables somehow, I want to use them with separate databases for some reasons, so don't suggest to merge them in one database with schemas

2 Answers 2

2

You can if you are using Sql Server 2005 and above by using Synonyms.

For example: Say you have three sql server databases. You could choose one to be the "main" database and create synonyms in the main database for the tables that are in the other two databases. Then you could use the synonym names when creating the entity models for the tables that are not in the main database.

Sign up to request clarification or add additional context in comments.

4 Comments

I've created synonyms, but they not appear I model any objects (views, tables, procedures) so how could I import this in my model.edmx ?
Could you create Views in the main database that are based on the external tables? Then Insert and Update via stored procedures?
I can think of two ways to get this to work with an edmx but I wouldn’t suggest either of them. The first way would be to manually edit the edmx to include the synonyms that you created. If you do this you’ll want to avoid using the designer because it will overwrite your changes (which defeats the purpose of using edmx). The second way would be to use a View to see the data and Stored Procedures to manipulate the data (as Colin mentioned). I think this option would be annoying because it would be less convenient to work with the data.
Personally, I’d suggest using the “code first” approach which is what my original answer had assumed. You could use the Entity Framework Power Tools to code gen all your entities and then you would just need to change the table names to the synonyms.
1

I don't think you can do this in one single model, but its possible to make two DbContext classes and then use the values from one to query the other. You wouldn't be able to use Lazy loading between them, but that's a small price to pay.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.