You can also do this with views (and a linked server if the other db is on a different server). This will keep you from having to manage/merge two separate edmx files. I've used this with a linked server for reading data from a second db on a different server but ran a few quick tests to see if updates/inserts/deletes were possible and they are.
I have zero experience with distributed transactions so the info related to distributed transactions may be good, bad, or a little bit of both. If your two db's are on the same server I ASSUME distributed transactions no longer apply.
There are a couple of things to keep in mind when using a linked server.
- When you modify the entities in the linked db tables and call
SaveChanges
on your context, this will try to start a distributed transaction so unless anyone knows how to stop that, you need to make sure the two servers are setup to handle distributed transactions. (I would assume this would be true using synonyms too).
- Inserts on entities with identity columns on the linked server throw an exception because ef tries to get the new id using
SCOPE_IDENTITY()
and it is null. I don't know if there is a way around this. I didn't have any problems updating or deleting entities on the linked server with identity columns.
On SQL Server A
- create a linked server to ServerB (skip this if db's are on the same server).
- create a view in
[ServerA].[MyDB]
for each table in [ServerB].[AnotherDB]
you want to access
In EDMX
- Add your views to the edmx file
- Clear the entity key setting from each property in the designer (including the actual pk)
- Reset the entity key for the actual pk
- Add associations as needed
- Save changes
For Updates/Inserts/Deletes
- right click on your edmx file and open with xml editor
- Navigate to the
StorageModel
-> Schema
-> EntityContainer
- Find the entityset for your entity and delete the
DefiningQuery
element
- Find the
store:Schema
attribute on the entity set and remove store:
so that it is just Schema
. Leave its value alone.
- Repeat steps 3 & 4 for each view from the linked server
- Save changes
Because using a linked server creates a distributed transaction I had to do a couple of things on the ObjectContext
before SaveChanges
was successful.
ctx.Connection.Open();
ctx.ExecuteStoreCommand("set xact_abort on");
ctx.SaveChanges();
ctx.Connection.Close();
You can probably create a custom ObjectContext
and override SaveChanges
to add this stuff in.