I have to create an application that will copy common configuration settings from one database to another database (same schema). I'm wondering if I can use one Entity Model to access both databases. Say it is stores and products that need to be copied. Can I use the same model to get a store from serverA.databaseA and then insert into server.databaseB?
Asked
Active
Viewed 116 times
1
-
You would need to instantiate two contexts with different connection strings, but yes, theoretically it is possible. You might run into errors if you try to insert an entity from context A into context B directly, but I'm sure there are ways around that, such as mapping, or detaching the object from the first context, etc. – cwharris Apr 25 '13 at 15:20
-
Thanks Christopher. How would you recommend doing something like this in .NET? I'm a SQL Server DBA\Developer who does just enough .NET to be dangerous/ – Jack Corbett Apr 25 '13 at 15:26
-
1Yes you can and it is very simple to set up (with code first). The only complication is with database generated identity values and the way I have dealt with this in the past is to generate them myself and avoid the need for identity columns. – qujck Apr 25 '13 at 15:27
-
as @qujck said, it should be easy with a code-first appoach, but seeing as how you're a DBA, I assume your database already exists. :) You should still be able to do it, but that's out of my realm of expertise, I believe. It would take me just as much research to come up with the answer as you. :) – cwharris Apr 25 '13 at 15:30
-
using code-first, you could use this constructor for DbContext: http://msdn.microsoft.com/en-us/library/gg679467(v=vs.103).aspx – cwharris Apr 25 '13 at 15:31
-
Thanks guys. At least I know I'm not trying something impossible. :-D – Jack Corbett Apr 25 '13 at 15:45
-
Talking about the code-first mostly (but connections etc. applies to all I think). As long as your entity models (your .cs model code) are the same - you can `just switch connections`. But there are some problems with it - check my post on that and the solution - [Switching connections](http://stackoverflow.com/questions/15926897/code-first-custom-connection-string-and-migrations-without-using-idbcontextfacto/15938194#15938194). However, if you want to 'mix' just an odd table here and there - that might be an issue as you models will not match. – NSGaga-mostly-inactive Apr 25 '13 at 16:32
1 Answers
1
You can have two similar DbSet
s in two different DbContext classes. As mentioned in comments, the real problem is to deal with identity columns and IMO with context attachments. I think best way is to handle identity columns manually and fetch data from db in a detached state.

Kamyar
- 18,639
- 9
- 97
- 171