Entity Framework Cannot find connection string - entity-framework

I have a stange problem.
In my solution, I have a "Model" directory. In that directory, I have created an entity model. When I create the model (using the wizard), it creates a new entry for connection string in my app.config (which is at the solution level).
However when I try to access the entity object constructor using the default constructor, I get the error: The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
I have a test application, where I have added a link to this app.config. From here I can access the entity object without any problem!
Thanks

Make sure the connection string is in the config file of the executing assembly. If you for instance use EF from af web site, you can copy the connection string from the app.config in the EF assembly to the web.config of the website assembly. Copy all of the connectionStrings-block:
<connectionStrings>
...
</connectionStrings>

Related

Web app with EF + database first not working on Azure

I have a ASP.NET MVC application which uses EF (v6) as data access layer. My application works fine on IIS Express and also when deployed to the server running IIS 7.5.
The problem is that I'm getting the following exception when I deploy it to Azure (Web Sites).
Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.
I've searched the web and I made sure my connection string starts with "metadata=" + checked my db context class' constructor to be sure it contains the correct name (in my case it's "name=PsDataEntities"))
My connection string looks like this: <add name="PsDataEntities" connectionString="metadata=res://*/PsDataModel.csdl|res://*/PsDataModel.ssdl|res://*/PsDataModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=SERVER_NAME;initial catalog=DB_NAME;user id=UID;password=PWD;
MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
Anybody had the same problems?
Any help is appreciated
I did a few more tests (like changing metadata in the connection string to use fully qualified names instead of '*') without success, then I decided to set my metadata (regarding .csdl/.ssdl/.msl) programatically with the help from this post. Application now works correctly when deployed to Azure.

Database Connection Error with ef-code-first

I'm new to ef code first and have just used the reverse engineer code first to create a model of an existing database on Microsoft SQL Server 2008.
The problem I'm having is that even though I'm providing User ID and Password in the connection string, it's giving me an authentication error while complaining about my computer name as if I were using Integrated Security (which I'm not.)
The error I get is this:
Cannot open database \"edmTestDBContext\" requested by the login. The login failed.\r\nLogin failed for user 'jwelty-thinkpad\jwelty'.
My connectionString is this:
Data Source=srv-123;Initial Catalog=edmTestDB;Persist Security Info=True;User ID=user;Password=userpass;MultipleActiveResultSets=True
It seams to me like it's ignoring my User ID and using my machine name instead.
It's interesting that the connection string was auto generated by the Entity Framework tool and it worked for building the model but not for actually connecting the model back to the source database.
Any thoughts on what's going on?
I do have full permissions with my username/password as this is what I use with Sql Server Management Studio and that's also how I created the database in the first place.
I tried adding "Integrated Security=False;" and that was no help.
It looks like EF isn't finding your connection string. Make sure that it is in the config file being used (you might need to copy it from the class library config to the application config) and that it either has the same name as the context class or that you provide DbContext with the name by calling the appropriate base constructor. For example:
public EdmTestDBContext()
: base("name=MyConnectionStringName")
{
}
There are some built-in conventions in EF Code-first such as using the name of derived context class from DbContext to find the related connection string in the .config file.
So if your context class is named BlogContext, it will look for the following connectionString first:
<connectionStrings>
<clear />
<add
name="BlogContext"
...

Querying Ef context using LinqPad: Argument Exception

I have added Ef connection in linqpad like following
As you can see connection is successfully added but when i want to query against this connection i get the following exception
The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.
it seems to be connected with connection string but how it would be solved, i have no idea. The context is defined in asp.net mvc project (no separate project for data access) and connection string is in web.Config file as usual
I had this same problem, I was able to solve it by following the instructions here
1) Find the path that LINQPad uses for its configuration file by excuting this: AppDomain.CurrentDomain.SetupInformation.ConfigurationFile.Dump()
This returned for me the following: C:\Program Files\LINQPad4\LINQPad.config
I was suprised this returned LINQPad.config instead of LINQPad.exe.config
which is what you would typically expect since most .NET applications name the > file the same as the executable.
Take your App.config and copy it to the location above naming the config
file whatever yours returned. In my case it was LINQPad.config
Close LINQPad or the TAB that you have opened to execute your assembly and reopen to get LINQPad to read the configuration file.
http://coding.infoconex.com/post/2012/06/01/Getting-LINQPad-to-read-your-applications-AppConfig-settings.aspx
Recent versions of LINQPad support direct connections to projects with a DbContext or ObjectContext. With that connection type, you can specify your app.config / web.config when setting up the connection.
http://www.kevinlabranche.com/blog/ConnectingLinqPadToEntityFrameworkCodeFirst.aspx

How to explicitly name the database when using Entity Framework Migrations 4.3

I've recently started using Entity Framework migrations and noticed that the database name is not pulling through for me when I run the Update-Database command.
My connectionstring is:
<connectionStrings>
<add name="DataContext" connectionString="Server=.\SQLEXPRESS;Initial Catalog=TestDB;Trusted_Connection=Yes;" providerName="System.Data.SqlClient" />
</connectionStrings>
The very first time I run Update-Database my database is created with the correct name TestDB. However, as soon as I make a change to one of my entities it will not update any longer for me unless I add a Start Up Project Name (I'm using a multi project solution):
Update-Database -StartUpProjectName "TestDB.Data"
This then makes another new database which migrations will always continue to use. I don't mind having to put in the StartUpProjectName command but is there a way to override the default name for the database this produces? It always creates the database as
TestDB.Data.DataContext
Is there a way to ensure that the database created when passing the StartUpProject name is just called TestDB or is this a limitation of using the StartUpProjectName setting?
As a note, I think the reason I need to specify the StartUpProjectName is that I have a multilayer project setup. The Migrations Configuration file is in my 'Data' project, the entities/models are in my 'Domain' project, etc. I also do not currently have any initialize options in my Global.asax.cs file as I would have used previously on code first ef 4.2. So in my project I just have a DataContext in my Data project and the Migrations Configuration in that project also.
EDIT:
Since I originally setup this question I stumbled onto the 'correct' way to name a database in a multiproject solution. While the answer below will work it does mean you are duplicating your web.config in another area which isn't an ideal solution. Instead you can just put the name into your DbContext by doing something like this (DataContext is just the name I used in my project):
public class DataContext : DbContext
{
public DataContext() : base("DatabaseNameHere")
{ }
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
public virtual void Commit()
{
base.SaveChanges();
}
}
Thanks,
Rich
You can avoid managing it in app.config by offering it as a parameter:
Update-Database -Verbose
-ConnectionString "CONNECTIONSTRING"
-ConnectionProviderName "System.Data.SqlClient"
-StartupProjectName WEBSITE_PROJECT -ProjectName MIGRATION_PROJECT
Easy-piezy, if you love to type endlessly.
When doing update-database you should specify the project that contains the migrations. Make sure that you have an app.config file in that project that contains the correct connection string.
When splitting up an application over several projects, the connection string used when running the app is the one of the project started. When migrating, the connection string used is the one of the project containing the migrations.
When I did a similar setup I had to add the connection string in two places. A bit awkward, but it works.
You can have your connection string stored in the web.config in your website project and the DBContext and migration files in another project and still share the same connection string. However you need to make sure that as well as setting the Data project (or whatever project has the DBContext etc. in it) as the default project for the Package Manager Console, you ALSO need to make sure that your website is set to the Default StartUp Project!!!
I cannot see this documented anywhere, but a frantic 24 hours of not being able to figure out why my migrations where suddenly being applied to a SQLExpress db, led me to this conclusion.
I tried with Latest EF5 from Nuget.
However Update-Database does not read the App.config from the project that contain the migrations (just like the answer 1 year ago) but it will only read *.config from start up project. It is great but I discover how Add-Migration and Update-Database find a suitable connection string here:
It trying to get "DefaultConnection" connection string first
Then it is trying to get the connection string name based on context class name. E.g. I have the MyContext class derived from DbContext so I can use the "MyContext" connection string name. Useful when I have multiple db connections.
If both the above connection string names are not found, it will fail and show no "DefaultConnection" connection string unless you supply the -ConnectionStringName parameter. See get-help Update-Database to view the help page in the Package Manager Console.
There is no retry or fallback attempt, so if the "DefaultConnection" contains a wrong connection string, it will simply show an error.
If both DefaultConnection and context name exist in the connection strings, DefaultConnection will take precedence.
I would prefer #2 become the first try because the name is more specific but the above steps is what EF5 Migrations do when trying to connect to the db.

Connection to Entity Framework from SSIS-package script task

From a script task in a SSIS-package I am calling a method in a DLL that uses Entity Framework. And when I´m debugging it stops in the DLL.
Error message: "The specified named connection is either not found in the configuration,
not intended to be used with the EntityClient provider, or not valid"
I had this error before, when I used the DLL from a website, but then I copied the Entity Framework Model Connection to the web.config, and it worked just fine.
What do I have to do in my script task in SSIS? Is this possible?
Your entity model assumes an application configuration file (such as web.config) exists, but because this is an SSIS package, the configuration model is different.
You need to add an SSIS configuration, put your entity connection string in there, map this into a variable in the package and then have the script task supply the connection string as an argument in the constructor of the data model. So something like:
EntityModel MyModel = new EntityModel(this.Dts.Variables["EntityConnectionString"]);
...and you should be good to go.