Entity Framework LocalDB connectionstring - c#

I find it hard to understand how Entity Framework in Visual Studio is dealing with a LocalDB.
In my project root folder I have a .mdf database file, let's call it MyDatabase.mdf
I'm using the MVVM pattern in my WPF application, so in my Model folder, I added an ADO.NET Entity Data Model (code-first from database).
Now in the Server Explorer view I always add a Data Connection to this MyDatabase.mdf, from here I can at least have some control over the database (like perform an EmptyDatabase procedure or whatever).
Now the most single annoying thing is that whenever I run my project, somehow under the Debug folder a new MyDatabase.mdf is created which has NO data in it.
In app.config there is this tag:
<connectionStrings>
<add name="DysphagiaModel"
connectionString="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\DysphagiaDB.mdf;integrated security=True;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework"
providerName="System.Data.SqlClient" />
</connectionStrings>
I just can't figure out why Entity Framework works this way, and I find it hard to find any good documentation for developers that are new to this. I'm used to working with PHP and MySQL, which really is a hell lot simpler than this. So this is really extremely frustrating, and I can't imagine I'm the only one having these issues with understanding how Visual Studio (and EF) works and how the underlying mechanics work.
Most articles and documentation out there already assume you know some mechanics, and they won't help you with referencing to what you need to know.
Anyway for this specific issue, how can I have my project use the database I have in my project's root folder?

During development Visual Studio creates a copy of the database (and other files) each time it rebuilds your app for debug / release mode. As Adriano posted this will create a new mdf file each time you run a fresh application (It rebuilds your app).
If you wish this not to happen every time, you can change the "Copy to Output" property and choose to ("Do Not Copy" or "Copy if Newer"). To do this you need to open the Solution Explorer, right click on your mdf file, goto properties and change the "Copy to Output Directory".
If you wish to access your data "inserted" on debug mode then you can reference your localdb copy on you bin/debug/[yourdb].mdf on your SQL Server Object Explorer, or create a new data conection (the last one not recommended). But remeber that every time you restart your debug this will start over unless you change your propierties.

Related

How to include LocalDB with project when built?

First of all, I am still very new to LocalDB and to ADO.NET as a whole, so if this is a stupid question (and it probably is, knowing me and new material), I apologize.
I am building a .NET 5 console application, and using ADO.NET to connect it to a LocalDB database. There have been a few snags, though. First of all, I have to double-click the database file in Visual Studio's Solution Explorer (I'm using Visual Studio 2022 Community Preview) in order for the app to be able to see the database. This was a mild annoyance when I was doing internal testing, but now that that's done, I can't expect all of my users to have Visual Studio.
Second, I currently have the database connection string as an absolute path:
static string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;Initial Catalog=P:\\PROJECTS\\NACS-TRACKER\\DATABASE.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
Obviously, this won't work any more now that I'm ready to have others test the app. Given that I'm new to this, I don't really know if relative paths would be appropriate here. If so, how would I go about doing it?
Finally, how would I make sure that the database file is included with the build? Thanks!

Entity Framework - Unable to load the specified metadata resource

I realise that this has been asked a number of times but I just can't seem to get the bottom of my issue. I'm getting the following error stack:
When I reflect out my dll I can see the following
Reading http://blogs.teamb.com/craigstuntz/2010/08/13/38628/ it suggests I'd expect to see the csdl, msl and ssdl files here, but they're not. They do exist here obj\Debug\edmxResourcesToEmbed though.
Never-the-less I tried to explicitly tell the web.config where to look by doing this:
...connectionString="metadata=res://DllName.dll/PaymentModel.csdl|res://DllName.dll/PaymentModel.ssdl|res://DllName.dll/PaymentModel.msl;provider=System.Data.SqlClient;provider ... />
Which just throws an error saying it cannot find the dll:
Unable to resolve assembly 'DllName.dll'.
Very similar to this unresolved SO question Unable to resolve assembly Model.dll
The final thing I tried was to change the metadata line to:
...connectionString="metadata=res://*/;provider=System.Data.SqlClient;provider ... />
This threw a message about sql ce which I'm not using - is there a way to get round this??
Is there anything else I can try? Or can anyone see where I'm going wrong? Some extra detais:
Using EF 6 EDMX set to "Embedded Resource"
Copy to output directory:"Do not copy"
Metadata artifact processing: "Embed in output
assembly"
Finally on this - if I set the EDMX from Embedded Resource to EntityDeploy then this will work locally but not build on the build server as it throws the exact same error as this SO question:
Could not find the Conceptual Schema node to embed as a resource for input file
But the fix doesn't seem to help and I can't install .NET 4.5 on the server unfortunately.
I have had the same problem.
After moving .edmx file with EF model to separate assembly mentioned error caused my headache: "Unable to load the specified metadata resource".
EF version 6.1
Solution:
Old value:
metadata=res://*/Data.DataModel.csdl
New value:
metadata=res://*/DataModel.csdl
Initially .edmx was under project's folder and I have moved it into project's root.
So I've got to the bottom of this, partly I think this was my fault. I'll put solutions to each issue I encountered below in case it helps anyone else.
Unable to load the specified metadata resource issue
This was caused by me setting the 'Metadata Artifact Processing' setting on the edmx model from "EntityDeploy" to "Embedded Resouce".
So this meant it just embedded the whole edmx file file into the dll and didn't generate the ssdl, msl and csdl files instead.
I guess you have to set this to EntityDeploy for this to work and generate these files correctly. Makes perfect sense and our bad over here.
Unable to resolve assembly 'DllName.dll'
This was resolved by Andrew in the comments above, thanks for the pointer on that.
Could not find the Conceptual Schema node to embed as a resource for input file
The key to this whole issue really is this, our build server is currently on Windows 2003, so can't have .NET 4.5 installed, locally we were using EF 6.1 running under .NET 4.0 on VS2013.
However for some reason it looks like we need to have .NET 4.5 installed on our build server to get this to build even though we're not using any of the 4.5 features and targetting the .NET 4 framework.
Downgrading to EF to 4.3 solved this issue for us in the short term. Not ideal but it worked.
you should specify the assembly fully qualified name and a path to your model file within it(separated by /), not the dll name
connectionString="metadata=res://Name.Of.The.Assembly, Culture=neutral, PublicKeyToken=8e2e51fcf4cf363e/Payment.PaymentModel.csdl|.........."
the same for ssdl and msl
Change the metaData
connectionString="metadata=res://*/Entities.csdl|res://*/Entities.ssdl|res://*/Entities.msl;
To
connectionString="metadata=res://*/;
The above change will fix the issue
I was having the same issue
System.Data.MetadataException: Unable to load the specified metadata resource
It turned out the Connection string which was generated earlier had all the edmx's name on it.
I took out all the model names from the connection string leaving only the below string in my metadata
"metadata=res://*/;provider=System.Data.SqlClient;provider
This worked for me.
Solution :
1) Open .edmx file from visual studio.
2) Click anywhere.
3) Should see edmx property window.
4) Change Namespace to the correct folder name.
5) 1: https://i.stack.imgur.com/6sZvo.png (select image for more details ).
If you're using the dotnet CLI
For newer visitors using the new dotnet build tooling to build Entity Framework 6.x based projects, know that it currently does NOT embed any metadata into the final build. So if you run from within VS it'll run, but if your CI scripts use dotnet then they will fail on the server until you switch back to msbuild. IMHO, this is a bug and the tools should handle this. You can chime on the GitHub thread if needed.
I actually received this identical error because my Entity Framework connection string was pointing to a valid database however it was the incorrrect database.
If you have the following instances in SQL Server:
MyDatabase1
MyDatabase2
Make sure that the connection string points to the same database that the .EDMX is wired up to and was generated from. Seems obvious enough, but when copying EF connection settings from 1 project to another this error was made and the net result was the Unable to load the specified metadata resource message. Once I used the correct connection string pointing to the correct database and assembly - the error was resolved.
The easiest thing to do is take the original connection string created in the .config file residing next to the .EDMX and copy where needed to make sure subtle or minor omissions/mistakes are not made causing EF to not load/connect correctly.
I was getting the same error. My connection string was as following
<add name="EmployeeDbContext" connectionString="metadata=res://*/EmployeeModel.csdl|res://*/EmployeeModel.ssdl|res://*/EmployeeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Sample;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I changed it to following and it fixed the problem
<add name="EmployeeDbContext" connectionString="server=.; database=Sample; integrated security=true;"
providerName="System.Data.SqlClient"/>
Also, be aware when moving the edmx file from say a web application to a data layer, (web.config - connection / app.config - connection) that you
change the connectionstring in the data layer AND the webservice layer.
(else one uses two different connection strings, and this causes such a problem)
The connection string "metadata=res" should be same as Edmx name. eg
metadata=res://*/EmployeeModel.csdl
this EDMX name should be EmployeeModel
I am sharing my code with another developer and he had this problem.No connection string differences. All the files OK...
I fixed it by setting
Metadata Artifact Processing from: "Embed in Output Assembly" to "Copy to output directory" ,
rebuilding the project,
and then setting it back again.
This worked, I assume, because the individual files (CSDL/MSL/SSDL files) were created in the output directory when it used "copy to output directory". Apparently there was a bug that required them for the embedded version to work.
Hope this helps :)
I hit this issue and it has bit me many, many, many times and I always forget how I fix it.
All I had to do is set the default.aspx as the start page.
Obviously this won't help everyone but in my case I have gone down the road of checking my config, connection string...
Hope this help someone, or at least the next time I google it I will find my fix. :)
I have used EF6 in my visual studio 2013. I have solved this by doing the following steps.
Right click on the Entity model
Open with XML(Text) editor
in tag set ProviderManifestToken="2008"
build solution
Hope it works for you..
I want to share my experience on this and how I solved it. In my case it happens because I copy and pasted my connection string on production server. My application was using Entity framework.
Problem was on metadata
I named my entity model as 'BetModel' but on my connection string I was using 'Entity' - 'res:///Entity.csdl|res:///Entity.ssdl|res://*/Entity.msl' on 'metadata' (reason was because i copy pasted it).
So my wrong ConnectionString was:
connectionString="metadata=res://*/Entity.csdl|res://*/Entity.ssdl|res://*/Entity.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=;persist security info=True;user id=;password=;MultipleActiveResultSets=True;App=EntityFramework""
and the corrected ConnectionString was:
<add name="BetEntities" connectionString="metadata=res://*/BetModel.csdl|res://*/BetModel.ssdl|res://*/BetModel.msl;provider=System.Data.SqlClient;provider connection string="data source=;initial catalog=;persist security info=True;user id=;password=;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I've hit this several times when moving between development machines after pulling down code from source control. I usually just have to explicitly rebuild the project with the EDMX file in it.
If you're trying to use more than one EDMX file and you have to put your new EDMX file in it's own namespace due to conflicts, when creating the EDMX file take note of the metadata the wizard shows you. That one is the correct one.
Then later if you are using EntityConnectionStringBuilder and are setting the Metadata there make sure you take into account the new namespace.
None of the answers here helped me as I had:
/EDMX1
/Namespace/EDMX2
and while the metadata for the EDMX1 is "edmx1.csdl|edmx1.ssdl|edmx1.msl"
The metadata for EDMX2 is "Namespace.edmx2.csdl ..."

New Connection fails during Add New Data Source Dialog

The Problem
If I have Visual Studio 2010, Service Pack 1 installed, and I go to Data, Add New Data Source and click Database, it brings up the standard Choose Your Data Connection wizard page.
On that page, if I have an existing connection configured, I can then select it, and add that data source to my project, no problems, no issues.
On the other hand, if I click New Connection... it just bombs out, wizard closes, as if I had done nothing. Now keep in mind, Visual Studio doesn't close, and there are no exceptions, errors, or warnings, the dialog window just disappears.
Unsuccessful Attempts to Resolve Issue
I've checked the simple things, using a debugger, and a valid machine config file, not sure what else I might be missing.
Using a Debugger
I tried starting a 2nd copy of Visual Studio as I did this, and
attaching a debugger to the process, with all exceptions checked in
my debug menu, and still nothing.
Validating machine.config file is valid
I backed up my machine.config file, and used another person's working machine's machine.config file, and I'm still having issues.
I have since reverted back to my own machine.config file.
I suspect the machine.config might be the issue, but I thought
taking a working one should work, unless I'm missing one of the
registered providers? I don't know enough about how this wizard
works behind the scenes though, or what sections/lines of the
machine.config file exactly drive the wizard.
Uninstalling all third-party database providers
I have recently tried uninstalling Oracle, SQLite, beta versions of SQL Server Compact Edition, and MySQL providers in hopes that one of them set a registry entry or configuration entry that was negatively impacting my ability to create new connections and the error still occurs.
Reinstalling Visual Studio
I reinstalled Visual Studio, complete uninstall, and reinstall, no extensions, or nothing, and the issue exists, definitely convinced its a configuration error at this point, I could use the expert opinion of someone who knows more about the configuration behind the scenes for this dialog though.
Any help in resolving the issue would be greatly appreciated.
Visual studio 2012 solution.
Close visual studio.
Open the event viewer, go to Application Log, and find Errors with source devenv.
Mine said
The following information was included with the event:
.NET Framework Data Provider for MySQL: An unexpected error occurred in the data provider.
Then i opened registry editor and went to:
HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0_Config\DataProviders\
And deleted the key that reffered to the faulty data provider
{c6882346-e592-4da5-80ba-d2eadcda0359}
(default) = .NET Framework Data Provider for MySQL
I have the same issue. Delete all records in event viewwr and works.
Start -> run
Type "eventvwr"
Select application
Select "Action" > "Clear All Events" from menu
Save or not as you wish the events backup. Do the same with "System"
Try using Server Explorer window to add your Connection.
Try defining your Connection String from Settings.settings file
Try moving/deleting all the *.datasource files from the project/solution before adding the connection
Try creating a new, empty solution and see if the problem is solution-indepentent
Try finding out what registry keys and files Visual Studio uses when the issue occurs with Process Monitor from Sysinternals
I have had the same issue today.
Solved it by removing a tag in machine.config file:
**32-bit**
%windir%\Microsoft.NET\Framework\[version]\config\machine.config
**64-bit**
%windir%\Microsoft.NET\Framework64\[version]\config\machine.config
Tag to remove:
<DbProviderFactories/>
The problem is that when the dataset is modified, the dataset is linked to the bi object. I solved the problem like this: I made a change and registered the dataset and it came up an error. I then undo it with CTRL + Z, the error is resolved. Then I moved forward with CTRL + Y, and the error went away. Thanks to this solution, I added the query, added a new table.

Can I commit changes to actual database while debugging C# in Visual Studio?

I am creating a C# application using Visual Studio that uses an SQLExpress database. When I hit f5 to debug the application and make changes to the database I believe what is happening is there is a copy of the database in the bin/debug folder that changes are being made to.
However, when I stop the debugging and then hit f5 the next time a new copy of the database is being put in the bin/debug folder so that all the changes made the last time are gone.
My question is:
Is there a way that when I am debugging the application I can have it make changes to the actual database and those changes are actually saved or will it only make changes to the copy in the bin/debug folder (if that is what is actually happening)?
I've seen similar questions, but I couldn't find an answer that said if it's possible to make those changes persistent in the actual .mdf file.
The reason I ask is because as I build this application I am continuously adding pieces and testing to make sure they all work together. When I put in test data I am using actual data that I would like to stay in the database. This would just help me not have to reenter the data later.
Thanks in advance for any help or information that could help me better understand the process.
Select the databases in Solution Explorer and change the "Copy to Output Directory" to "Copy if newer". Later, when you finally get the final version, copy paste the databases in debug folder to your source folders
The problem with 'Copy if newer' is that when you make changes to any part of the structure of the database, that change is to the version in your Project directory and not to the version you are building on in the Debug directory.
Also, when you try a non-debug run you are not using the copy you have been chaging in the debug location.
I normally use a Postgresql, but as this is a new computer and I discovered MS do this Lite version, decided to give it a try. I have a lot of data which is historic that I want in the table, then some manual manipulation with a bit of SQL, Then I can carry on creating the actual functionality of the database.
You can not just copy the altered version into the project directory, because there is a log file and no one seems to know what is in there but Microsoft desperately need that to match your database file in some way. (I am guessing you already tried that too).
I didn't want to have to start from scratch every time I ran it, and just like you I found no solutions. So in a desperate move I copied the version in Debug to a tmp directory. Then deleted the version in the project solution explorer.
Then I dragged and dropped the version in tmp into solution explorer. (Everything in it is structurally the same as the original, except as stated below)
That did it, it recreated that Log file. Now my debug sessions start with a ready loaded data.
Words of warning.
1) Changing the database structure.
In your solution explorer, the the Linq to SQL DBML file, if you have changed some structural part of the database in code (which is where I tend to do it), right click on the DBML file and go into design view. Then drag into the design any new tables or views that you have added.
2) Because having to delete and drag in the database feels a bit dodgy, write yourself a function that runs on Form_Open when in debug mode that copies your database file such as
\MyDatabaseBackup\myDatabase_date_time.mdb
Remembering that if you do go back to a previous version at any time you need to rename it myDatabase.mdb
Copy database to some proper location and change the connection string in config file to point to that only, it is only a suggestion as not sure what type of app. it is.

MetadataException: Unable to load the specified metadata resource

All of a sudden I keep getting a MetadataException on instantiating my generated ObjectContext class. The connection string in App.Config looks correct - hasn't changed since last it worked - and I've tried regenerating a new model (edmx-file) from the underlying database with no change.
Anyone have any ideas?
Further details: I haven't changed any properties, I haven't changed the name of any output assemblies, I haven't tried to embed the EDMX in the assembly. I've merely waited 10 hours from leaving work until I got back. And then it wasn't working anymore.
I've tried recreating the EDMX. I've tried recreating the project. I've even tried recreating the database, from scratch. No luck, whatsoever.
This means that the application is unable to load the EDMX. There are several things which can cause this.
You might have changed the MetadataArtifactProcessing property of the model to Copy to Output Directory.
The connection string could be wrong. I know you say you haven't changed it, but if you have changed other things (say, the name of an assembly), it could still be wrong.
You might be using a post-compile task to embed the EDMX in the assembly, which is no longer working for some reason.
In short, there is not really enough detail in your question to give an accurate answer, but hopefully these ideas should get you on the right track.
Update: I've written a blog post with more complete steps for troubleshooting.
A minor amendment helped me with this problem.
I had a solution with 3 project references:
connectionString="metadata=res://*/Model.Project.csdl|res://*/Model.Project.ssdl|res://*/Model.Project.msl;
which I changed to:
connectionString="metadata=res://*/;
You can get this exception when the Edmx is in one project and you are using it from another.
The reason is Res://*/ is a uri which points to resources in the CURRENT assembly. If the Edm is defined in a different assembly from the code which is using it, res://*/ is not going to work because the resource cannot be found.
Instead of specifying ‘*’, you need to provide the full name of the assembly instead (including public key token). Eg:
res://YourDataAssembly, Version=1.0.0.0, Culture=neutral, PublicKeyToken=abcdefabcedf/YourEdmxFileName.csdl|res://...
A better way to construct connection strings is with EntityConnectionStringBuilder:
public static string GetSqlCeConnectionString(string fileName)
{
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlServerCe.3.5";
csBuilder.ProviderConnectionString = string.Format("Data Source={0};", fileName);
csBuilder.Metadata = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl",
typeof(YourObjectContextType).Assembly.FullName);
return csBuilder.ToString();
}
public static string GetSqlConnectionString(string serverName, string databaseName)
{
SqlConnectionStringBuilder providerCs = new SqlConnectionStringBuilder();
providerCs.DataSource = serverName;
providerCs.InitialCatalog = databaseName;
providerCs.IntegratedSecurity = true;
var csBuilder = new EntityConnectionStringBuilder();
csBuilder.Provider = "System.Data.SqlClient";
csBuilder.ProviderConnectionString = providerCs.ToString();
csBuilder.Metadata = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl",
typeof(YourObjectContextType).Assembly.FullName);
return csBuilder.ToString();
}
If you still encounter the exception, open the assembly in reflector and check the filenames for your .csdl, .ssdl and .msl files. When the resources have different names to the ones specified in the metadata value, it’s not going to work.
I had a similar error. I had recreated the project (long story), and pulled everything over from the old project. I hadn't realized that my model had been in a directory called 'Model' before, and was now in a directory called 'Models'. Once I changed the connection in my Web.Config from this:
<add name="RecipeManagerEntities" connectionString="metadata=res://*/Model.Recipe.csdl
to this:
<add name="RecipeManagerEntities" connectionString="metadata=res://*/Models.Recipe.csdl
Everything worked (changed Model to Models). Note that I had to change this three places in this string.
And a quick way to check the model name without Reflector.... look for the directory
...obj/{config output}/edmxResourcesToEmbed
and check that the .csdl, .msl, and .ssdl resource files are there. If they are in a sub-directory, the name of the sub-directory must be prepended to the model name.
For example, my three resource files are in a sub-directory Data, so my connection string had to be
metadata=res://*/Data.MyModel.csdl|res://*/Data.MyModel.ssdl|res://*/Data.MyModel.msl;
(versus metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;).
I also had this problem and it was because the connectionstring in my web.config was slightly different than the one in the app.config of the assembly where my EDMX is located. No idea why it changed, but here are the two different versions.
App.config:
<add name="SCMSEntities" connectionString="metadata=res://*/Model.SMCSModel.csdl|res://*/Model.SMCSModel.ssdl|res://*/Model.SMCSModel.msl;provider=System.Data.SqlClient;provider connection string="data source=SANDIEGO\sql2008;initial catalog=SCMS;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Web.config:
<add name="SCMSEntities" connectionString="metadata=res://*/Model.SCMSModel.csdl|res://*/Model.SCMSModel.ssdl|res://*/Model.SCMSModel.msl;provider=System.Data.SqlClient;provider connection string="data source=SANDIEGO\sql2008;initial catalog=SCMS;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
What fixed it was simply copying the app.config string (notice the small difference at the end - instead of "App=EntityFramework" it wanted "application name=EntityFramework") into the web.config and problem was solved. :)
This happens to me when I do not clean solution before build new .edmx designer. So just don’t forget to clean solution before you build new .edmx designer. This helps me to skip lot more issues with this one. Bellow the navigation details provided incase you are new in visual studio.
Click->Build->Clean Solution
Then Click->Build->Rebuild Solution
Hope this helps. Thanks everyone
This happened to me when I accidentally switched the Build Action of the edmx file (appears under Properties in the IDE) from 'EntityDeploy' to 'None'. EntityDeploy is what populates the metadata for you: see http://msdn.microsoft.com/en-us/library/cc982037.aspx
If you are using the edmx from a different project, then in the connection string, change...
metadata=res://*/Data.DataModel.csdl
...to...
metadata=res://*/DataModel.csdl
Sometimes i see this error in my project. I solve that by
1 - Right click on EDMX file
2 - Select Run Custom Tool option
3 - Rebuild project
I've just spent a happy 30 minutes with this. I'd renamed the entities object, renamed the entry in the config file, but there's more ... you have to change the reference to the csdl as well
very easy to miss - if you're renaming, make sure you get everything ....
I had the same problem. I looked into my complied dll with reflector and have seen that the name of the resource was not right. I renamed and it looks fine now.
For my case, it is solved by changing the properties of edmx file.
Open the edmx file
Right click on any place of the EDMX designer
choose properties
update Property called "Metadata Artifact Processing" to "Embed in Output Assembly"
this solved the problem for me.
The problem is, when the container try to find the meta data, it cant find it. so simply make it in the same assembly.
this solution will not work if you have your edmx files in another assembly
I spent a whole day on this error
if you are working with n-tear architecture
or you tried to separate Models generated by EDMX form DataAccessLayer to DomainModelLayer
maybe you will get this error
First troubleshooting step is to make sure the Connection string in webconfig (UILayer)and appconfig (DataAccessLayer) are the same
Second which is Very important the connection string
connectionString="metadata=res://*/Model.csdl|res://*/Model.ssdl|res://*/Model.msl;provid.....
which is the problem
from where on earth I got Modelor whatever .csdl in my connection string where are they
here I our solution look at the picture
hope the help you
I was able to resolve this in Visual Studio 2010, VB.net (ASP.NET) 4.0.
During the entity model wizard, you will be able to see the entity connection string. From there you can copy and paste into your connection string.
The only thing I was missing was the "App_Code." in the connections string.
entityBuilder.Metadata = "res://*/App_Code.Model.csdl|res://*/App_Code.Model.ssdl|res://*/App_Code.Model.msl"
After hours of googling and trying to solve none of the solutions suggested worked. I have listed several solution here. I have also noted the one that worked for me. (I was using EF version 6.1.1, and SQL server 2014 - but an older DB)
Rebuilding the project and try again.
Close and open VS - I don't know how this works
make sure if you have placed the .EDMX file inside a Directory, make sure you include the Directories in your ConnectionString. for example mine is inside DAL folder. SO it looks like this: connectionString="metadata=res://*/DAL.nameModel.csdl|res://*/DAL.nameModel.ssdl|res://*/DAL.nameModel.msl;(these are files. to see them you can toggle Show All Files in solution explorer, under ~/obj/.. directory)
...and many more which I had tried [like: reverting the EntityFramework version to a later version(not sure about it)]
what worked for me:
from this article here, it helped me solve my problem. I just changed my ProviderManifestToken="2012" to ProviderManifestToken="2008" in the EDMX file. To do this:
Solution Explorer
Right click over file .edmx
Open with..
Editor XML
Change ProviderManifestToken="XXXX" with 2008
I hope that helps.
In my case, this issue was related to renaming my model's edmx file... correcting the app.config connection string for the csdl/ssdl/msl files fixed my issue.
If you're using the EF 4.0 designer to generate your csdl/ssdl/msl, these 3 "files" will actually be stored within the model's main edmx file. In this case, the post by Waqas is pretty much on the mark. It's important to understand that "Model_Name" in his example will need to be changed to whatever the current name of your model's .edmx file (without the .edmx).
Also, if your edmx file is not at the root level of your project, you need to preface Model_Name with the relative path, e.g.
res://*/MyModel.WidgetModel.csdl|res://*/MyModel.WidgetModel.ssdl|res://*/MyModel.WidgetModel.msl
would specify the csdl/ssdl/msl xml is stored in the model file 'WidgetModel.edmx' which is stored in a folder named 'MyModel'.
The ultimate solution (even after recreating the database on two other machines, as well as the EDMX and other sundries) was to not use the first edition of Entity Framework. Looking forward to evaluating it again in .NET 4.0.
After running into the same problem again and searching all over for an answer, I finally found someone who'd had the same problem. It appears that the connection string wasn't correctly generated by Visual Studio's wizard, and the link to the metadata resources was missing an important path.
v1.0 BUG?: Unable to load the specified metadata resource. Scripts != Models
Update 2013-01-16: Having transitioned to almost exclusively using EF Code First practices (even with existing databases) this problem is no longer an issue. For me, that was a viable solution to reducing the clutter from auto-generated code and configuration and increasing my own control over the product.
My issue and solution, the symptoms were the same "Unable to load the specified metadata resource" but the root cause was different. I had 2 projects in solution one was the EntityModel and the other the solution. I actually deleted and recreated the EDMX file in the EntityModel.
The solution was that I had to go back to the Web Application project and add this line into the config file. The new model had changed a few items which had to be duplicated in the "other" project's Web.Config file. The old configuration was no longer good.
<add name="MyEntities"
connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;
provider=System.Data.SqlClient;
provider connection string="
data source=Q\DEV15;initial catalog=whatever;
user id=myuserid;password=mypassword;
multipleactiveresultsets=True;
application name=EntityFramework""
providerName="System.Data.EntityClient" />
I have written this helper class to create instances of ObjectContext objects when they are defined in a different project than the project using it. I parse the connection string in the config file and replace '*' by the full assembly name.
It is not perfect because it uses reflection to build the object, but it is the most generic way of doing it that I could find.
Hope it helps someone.
public static class EntityHelper<T> where T : ObjectContext
{
public static T CreateInstance()
{
// get the connection string from config file
string connectionString = ConfigurationManager.ConnectionStrings[typeof(T).Name].ConnectionString;
// parse the connection string
var csBuilder = new EntityConnectionStringBuilder(connectionString);
// replace * by the full name of the containing assembly
csBuilder.Metadata = csBuilder.Metadata.Replace(
"res://*/",
string.Format("res://{0}/", typeof(T).Assembly.FullName));
// return the object
return Activator.CreateInstance(typeof(T), csBuilder.ToString()) as T;
}
}
For all of you SelftrackingEntities Users ,
if you have followed the Microsoft Walk-through and separated the Object context class into
the wcf service project (by linking to the context .tt) so this answer is for you :
part of the shown answers in this post that includes code like :
... = string.Format("res://{0}/YourEdmxFileName.csdl|res://{0}/YourEdmxFileName.ssdl|res://{0}/YourEdmxFileName.msl",
typeof(YourObjectContextType).Assembly.FullName);
WILL NOT WORK FOR YOU !! the reason is that YourObjectContextType.Assembly now resides in a different Assembley (inside the wcf project assembly) ,
So you should replace YourObjectContextType.Assembly.FullName with -->
ClassTypeThatResidesInEdmProject.Assembly.FullName
have fun.
With having same problem I re-created edmx from Database.
Solves my problem.
Exception is because compiler pointing to non existing Metadata so just Copy app.config connectionstring to Web.config ConnectionString
I was having problems with this same error message. My issue was resolved by closing and re-opening Visual Studio 2010.
Had same issue because I renamed an assembly.
I had to also rename it in AssemblyTitle and AssemblyProduct attributes in project Properties/AssemblyInfo.cs, and also deleting and re adding the reference to the edmx file.
Then it worked just fine.
I also had the same problem and solution as per Rick, except that I was importing an existing .edmx to a new project, and while the base namespace didn't matter it was imported into a different subdirectory so I also had to update the connection string inside Web.Config in three places, to include the different subdirectory naming:
I had the same problem with a solution which contained projects in a Solution Folder, when they were moved to the Solution Root (in order to overcome a suspected bug with the Mvc3AppConverter due to project locations).
Although the solution compiled after all* project references were re-added as needed, the error was thrown when the website was fired up.
The EDMX is in one of the projects which was moved (the 'Data' project), but of course the lack of a reference to the Data project didn't cause a compile error, just a run-time error.
Simply adding the missing reference to the primary project resolved this problem, no need to edit the connection at all.
I hope this helps someone else.
As for me, I had separated Data Access Layer and User Interface layer.
So I have entity connection string for each layer.
Before I modify these two separated connection strings to be the same, I still found that below error.
Unable to load the specified metadata resource
So I make to be the same connection strings for those two layers (DAL , UI), It work perfect.
My solution is to make all connection string to be the same no matter where they already presented.
I had this problem yesterday and was looking at my code in debug and the output from SQL Profiler.
What I couldn't understand, before I read and understood this post, was why EntityFramework was throwing this error as it was calling the DB. I was looking through hundreds of lines in SQL Profiler trying to work out what was wrong with the database model. I couldn't find anything like the call I was expecting, and to be honest I wasn't certain what I was looking for.
If you are in this position, check the connection string. My guess is that before EntityFramework creates its SQL it will check the model, specified in the metadata part of the connection string. In my case it was wrong. EntityFramework wasn't even making it as far as the DB.
Make sure the names are correct. Once I got that sorted out, I was then seeing calls in SQL Profiler where the ApplicationName was 'EntityFramework' with SQL calling the expected tables.
A poor app.config or web.config file can do this.. I had copied the app.config connection string to my web.config in my UI and ended up entering:
<connectionStrings>
<connectionStrings>
<add name="name" connectionString="normalDetails"/>
</connectionStrings>
</connectionStrings>

Categories