(This used to be a 2-part question, but since the second part is literally the important one, I decided to split this into two separate posts. See Using Serialization to copy entities between two ObjectContexts in Entity Framework for the second part.
I want to create a fairly generic "cloner" of databases for my entity model. Also, I might need to support different providers and such. I'm using ObjectContext
API.
I am aware of this question already and the EntityConnectionStringBuilder MDSN documentation example, but I need to know if there is a programmatic way to obtain the values to initialize the Provider
and Metadata
properties of an EntityConnectionStringBuilder
?
using (var sourceContext = new EntityContext()) {
var sourceConnection = (EntityConnection) sourceContext.Connection;
var targetConnectionBuilder = new EntityConnectionStringBuilder();
targetConnectionBuilder.ProviderConnectionString = GetTargetConnectionString();
targetConnectionBuilder.Provider = "System.Data.SqlClient"; // want code
targetConnectionBuilder.Metadata = "res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl"; // want code
using (var targetContext = new EntityContext(targetConnectionBuilder.ConnectionString)) {
if (!targetContext.DatabaseExists())
targetContext.CreateDatabase();
// how to copy all data from the source DB to the target DB???
}
}
That is, is there a way to fetch the
"System.Data.SqlClient"
"res://*/EntityModel.csdl|res://*/EntityModel.ssdl|res://*/EntityModel.msl"
from somewhere and not use literal values?
You should be able to use res://*/
to tell Entity Framework to search for all .csdl, .ssdl and .msl files in the calling assembly. Alternatively, use res://assembly full name here/
to search in a specific assembly. Note that both these syntaxes will load all found files, which works fine until you have several .edmx in the same assembly, resulting in several CSDL/SSDL/MSL files (an .edmx file is basically a concatenation of those three files). More information on MSDN.
If you want more control, use Assembly.GetManifestResourceNames to list all resources in a given assembly, and match the .csdl/.ssdl/.msl resources manually together, then build your metadata string manually from those resource names.
The provider can be found in the SSDL file in the Provider attribute of the root node. Once you have the correct file name, Use GetManifestResourceStream
and read the file as XML. The code should look like this:
using (var stream = assembly.GetManifestResourceStream("EntityModel.ssdl")) {
XDocument document = XDocument.Load(stream);
string provider = document.Root.Attribute("Provider").Value;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With