How should I edit an Entity Framework connection string? - entity-framework

I recently had to edit my app.config file to change the connection string for an Entity Framework data model (.edmx file). But I'd like to know: Is there a way to edit the EF connection string using the designer?
The original connection string is auto-generated by the Entity Data Model wizard. The connection string then cannot be changed - it remains disabled in the properties window of the .edmx designer. I like to avoid editing XML by hand if I can (in app.config), so I was wondering if there is a way to get back into the original wizard screen to make connection string changes and let the tool edit the app.config file for me.

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.
Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.

You normally define your connection strings in Web.config. After generating the edmx the connection string will get stored in the App.Config. If you want to change the connection string go to the app.config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.
In the output window it will show something like this,
Generated model file: UpostDataModel.edmx.
Loading metadata from the database took 00:00:00.4258157.
Generating the model took 00:00:01.5623765.
Added the connection string to the App.Config file.

Follow the next steps:
Open the app.config and comment on the connection string (save
file)
Open the edmx (go to properties, the connection string
should be blank), close the edmx file again
Open the app.config and uncomment the connection string (save file)
Open the edmx, go to properties, you should see the connection string uptated!!

Open .edmx file any text editor change the Schema="your required schema" and also open the app.config/web.config, change the user id and password from the connection string. you are done.

Related

T4 and Edmx conflict - "input file appears to be using a schema version not supported by this template"

I'm getting a warning from the T4 when the input file is a EF5 edmx.
Running transformation: The input file appears to be using a schema
version not supported by this template. This may lead to compile
errors. Please use 'Add New Generated Item' to add an updated
template.
Any idea why this is happening?
I once got this issue once when I upgraded an old project to .NET Framework 4.7.
If that is the case here too, then the *.tt file is deprecated now. It is a T4 generator file, which will create C# source required to access your entity objects and needs to be replaced. Do the following to update it (assuming you're using database first approach):
Remove the current (deprecated) *.tt file (exclude it from project and delete it)
Open the *.edmx file in the solution explorer by double-clicking it. The data classes diagrams are opening up.
Right-Click on a free space in the data classes visualization (your EF data model) and select "Update model from database..." in the context menu
Specify and test data connection (to ensure it is successful)
Now what happens in the background is that a new *.tt file will be generated. Once that is completed, rebuild your solution and the error should disappear.
But be aware that you likely have to do more changes afterwards, because there have been a couple of breaking changes in the newer versions of EF, which I have described here.

How to write an Enterprise Library dataConfig.config file?

I have 'inherited' a test harness application which uses Enterprise Library for its SQL data access. In the app.config file (enterpriselibrary.configurationSettings), it references a "configurationSection" with a path to "dataConfig.config", which is encrypted. I would like to change the database connection properties, but EntLibConfig.exe will not open the dataConfig.config or app.config (I have the FileKeyAlgorithmPairStorageProviderData file).
The test harness application runs, so its configured ok.
I can, in code, using (Microsoft.Practices.EnterpriseLibrary.Data.Configuration.ConfigurationManager.GetConfiguration("dataConfiguration")) read the data configuration, and can navigate all the instances and connection strings (security isn't an issue for this test harness). I can dump everything I need to a hand-crafted XML file (using GetType().AssemblyQualifiedName to get the full name for the classes which read the config file) and then change the app.config to read my new, unencrypted, xml dataConfig file.
All is fine, I can now change my database config settings.
However... given that ConfigurationManager.GetConfiguration("dataConfiguration") returns a fully populated instance of a DatabaseSettings object, is there not a method I can call which will write the XML file (dataConfig.config) for me ?
I appreciate that this is probably a really big hammer way to edit the data configuration, but after half a day of trying, I fell back on the old coding maxim... if you can't find the tool to do what you want, write your own !
Thanks
Well... turns out that its not that hard.
I added a new "configurationSection" to my app.config (dataConfiguration2), with encrypt set to false, with a path pointing to an new empty text file (dataConfiguration.config2). I then copied my encrypted dataConfiguration details using the following code:
using Entlib = Microsoft.Practices.EnterpriseLibrary.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data.Configuration;
:
DatabaseSettings settings = (DatabaseSettings)Entlib.ConfigurationManager.GetConfiguration("dataConfiguration");
Entlib.ConfigurationManager.WriteConfiguration("dataConfiguration2", settings);
...and it filled the empty file with the (unencrypted) configuration details.

Not filePath attribute in Enterprise Library 4.0 Configuration source block

I tried to follow this tutorial but couldn't find File entry in properties windows. When I tried to add filePath attribute manually (taken from same tutorial) i get following error "Parser Error Message: Unrecognized attribute 'filePath'. Note that attribute names are case-sensitive."
alt text http://img10.imageshack.us/img10/2403/configurationsourceprop.png
To find the File entry, you need to bring up the properties window (if it's not open) by hitting F4. Then click on the file configuration source element in the Enterprise Library configuration tool. This will display the Name and File properties that can be set.
Update
Thanks for the screen shot. To get the File Configuration Source, right click on Configuration Sources and then select New->File Configuration Source. Then you will be able to set the File property in that new element.

Entity Framework: Each type name in a schema must be unique

I'm doing a very non-standard build of Entity Framework. I've used EdmGen2 to generate edmx off of a db, and split the component csdl, msdl and ssdl files into their own files. The metadata in the connection string to them looks like this:
C:\Downloads\EDM | filename.csdl | filename.msdl | filename.ssdl
I have a unit test that does nothing but try to open the connection, and I get this error (along with a lot of other chaff):
"Each type name in a schema must be unique"
If I go into the csdl manually and add a "1" to the names, it eventually moves onto the msdl file and starts complaining about it. Clearly, somehow the schema is getting double-defined in the open operation...
There is no reference to the edmx in the test or dependent project. In fact, there are no references to any of those, as this is a project for generating all this stuff dynamically at run-time.
I've seen the Julie Lehrman / Don't Be Iffy post, and it doesn't appear to be that problem.
TIA...
Figured it out...the Metadata workspace is apparently hard coded to look for the three files (which makes sense), and when I removed the directory specification in the metadata tag, it all started working. My metadata attribute now looks like this:
C:\Downloads\filename.csdl | C:\Downloads\filename.msdl | C:\Downloads\filename.ssdl
So I think it's an either / or proposition: either specify the directory where the files are located, or the individual file locations.

MetadataException when using Entity Framework Entity Connection [duplicate]

This question already has answers here:
MetadataException: Unable to load the specified metadata resource
(47 answers)
Closed 6 years ago.
This code:
using (EntityConnection conn = new EntityConnection("name=ELSCommonEntities"))
{
conn.Open();
}
Gives me the following error:
Test method ELS.Service.Business.IntegrationTest.Base.ServiceBaseIntegrationTest.StartLoggingTestMethod threw exception: System.Data.MetadataException: Unable to load the specified metadata resource..
With the following stack trace:
System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.LoadResources(String assemblyName, String resourceName, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
System.Data.Metadata.Edm.MetadataArtifactLoaderCompositeResource.CreateResourceLoader(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
System.Data.Metadata.Edm.MetadataArtifactLoader.Create(String path, ExtensionCheck extensionCheck, String validExtension, ICollection`1 uriRegistry, MetadataArtifactAssemblyResolver resolver)
System.Data.EntityClient.EntityConnection.SplitPaths(String paths)
System.Data.EntityClient.EntityConnection.GetMetadataWorkspace(Boolean initializeAllCollections)
System.Data.EntityClient.EntityConnection.InitializeMetadata(DbConnection newConnection, DbConnection originalConnection, Boolean closeOriginalConnectionOnFailure)
System.Data.EntityClient.EntityConnection.Open()
ELS.Service.Business.Base.ServiceBase.StartLogging(String userWindowsLogon) in C:\C-TOM\ELS-RELEASE1\ELS.Service.Business\Base\ServiceBase.cs: line 98
ELS.Service.Business.IntegrationTest.Base.ServiceBaseIntegrationTest.StartLoggingTestMethod() in C:\C-TOM\ELS-RELEASE1\ELS.Service.Business.IntegrationTest\Base\ServiceBaseIntegrationTest.cs: line 65
However, this code which uses the same connection string:
using (ELSCommonEntities db = new ELSCommonEntities())
{
var res = from c in db.Logging
select c;
int i = res.Count();
}
Does not give an error.
The connection string is:
<add name="ELSCommonEntities" connectionString="metadata=res://*/Common.CommonModel.csdl|res://*/Common.CommonModel.ssdl|res://*/Common.CommonModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=els5_demo;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
I have also opened up the dll in reflector and the metadata looks ok.
Found the problem.
The standard metadata string looks like this:
metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl
And this works fine in most cases. However, in some (including mine) Entity Framework get confused and does not know which dll to look in. Therefore, change the metadata string to:
metadata=res://nameOfDll/Model.csdl|res://nameOfDll/Model.ssdl|res://nameOfDll/Model.msl
And it will work. It was this link that got me on the right track:
http://itstu.blogspot.com/2008/07/to-load-specified-metadata-resource.html
Although I had the oposite problem, did not work in unit test, but worked in service.
I had the same error message, and the problem was also the metadata part of the connection string, but I had to dig a little deeper to solve it and wanted to share this little nugget:
The metadata string is made up of three sections that each look like this:
res://
(assembly)/
(model name).(ext)
Where ext is "csdl", "ssdl", and "msl".
For most people, assembly can probably be "*", which seems to indicate that all loaded assemblies will be searched (I haven't done a huge amount of testing of this).
This part wasn't an issue for me, so I can't comment on whether you need the assembly name or file name (i.e., with or without ".dll"), though I have seen both suggested.
The model name part should be the name and namespace of your .edmx file, relative to your assembly.
So if you have a My.DataAccess assembly and you create DataModels.edmx in a Models folder, its full name is My.DataAccess.Models.DataModels. In this case, you would have "Models.DataModels.(ext)" in your metadata.
If you ever move or rename your .edmx file, you will need to update your metadata string manually (in my experience), and remembering to change the relative namespace will save a few headaches.
There are several possible catches.
I think that the most common error is in this part of the connection string:
res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;
This is no magic. Once you understand what is stands for you'll get the connection string right.
First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data.
Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.
Now the yyy part. That's a resource name in the xxx assembly.
It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog
The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.
Your final EF connection string may look like this:
res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;
As Shiraz Bhaiji answered, the metadata=res:///Model.csdl|res:///Model.ssdl|res://*/Model.msl was the case.
However I still had problems with constructing the proper string based on my Model localization, namespaces and assemby name. The very simple solution was to rename the .edmx file in Visual Studio(after than rename and get back to the original name), which triggered the automatic refreshing of the string in my Web.config
I had the same problem with three projects in one solution and all of the suggestions didn't work until I made a reference in the reference file of the web site project to the project where the edmx file sits.
I moved my Database First DataModel to a different project midway through development. Poor planning (or lack there of) on my part.
Initially I had a solution with one project. Then I added another project to the solution and recreated my Database First DataModel from the Sql Server Dataase.
To fix the problem - MetadataException when using Entity Framework Entity Connection. I copied my the ConnectionString from the new Project Web.Config to the original project Web.Config. However, this occurred after I updated my all the references in the original project to new DataModel project.
It might just be a connection string error, which is solved by the above process, but if you are using the dll's in multiple projects then making sure the connection string is named properly will fix the error for sure.
I had this problem when moving my .edmx database first model from one project to another.
I simply did the following:
Deleted the connection strings in the app.config or web.config
Deleted the 'Model.edmx'
Re-added the model to the project.