Entity Framework Migration cant find connection string in App.config file - c#

I have a second project in my solution called DataAccess (.NET Framework Class Library) for models. I set my main asp .net mvc project as start up and from package manager console I set DataAccess as default. I already have an existing database. So I installed Entity Framework in DataAccess layer using package-install command to get the latest. Then I added an Entity Data Model. But whenever I try to run enable-migrations from PM it shows that No connection string named 'MAHMHEntities' could be found in the application config file. Although there is a connectionString in App.config called MAHMHEntities. In my MAHMHEntities.cs class I have declared the connection string:
namespace DataAccess.Entities
{
using System.Data.Entity;
public partial class MAHMHEntities : DbContext
{
public MAHMHEntities()
: base("name=MAHMHEntities")
{
}
//other dbset classes
}
}
In DataAccess layer I have App.config file that has two connectionString, I added the DefaultConnection myself :
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQL2014;Initial Catalog=MAHMH;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
<add name="MAHMHEntities" connectionString="data source=.\SQL2014;initial catalog=MAHMH;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
</connectionStrings>
Whichever connection I use I always get the same error when I try to enable migration. Entity Framework version is 6.2.0.

You need to set Data access project as start up project. Or you can add your connection string to web application's(Which is currently start up project) web.config

Related

Entity Framework connection string without password

before I was using a connection string with integrated security.
Now I switched it to username/password and created a new user in my SQL server.
I generated a new connection string with the server explorer in visual studio by adding a new connection (I didnt really added a connection there, I just used the wizard and copied the connection string for the app.config).
then I had to update-database and it worked.
But now I recognized that there is no password in my new connection string.
How does it work? I can't find the password anywhere...
There are a couple ways:
1: Add the string to the constructor of your Context.
public class Context: DbContext
{
public SchoolDBContext() : base("connectionstring")
{
}
}
2: webconfig
<configuration>
<connectionStrings>
<add name="putYourEntityName" connectionString="putYourConnectionStringHere" providerName="System.Data.EntityClient"/>
</connectionStrings>
</configuration>
As referenced from here: Entity Framework Connection String in App.Config

Web Api project with another data project both have entity framework only wanting connection string in data project

I have 2 projects: 1 Web api (ReportingApi) 2. Data (ReportingApi.Data)
Web Api will not connect to the class library (Data ) project without a connectionstring in web.config that is duplicate of my connectionstring in my Data project app.config.
Both have
<connectionStrings>
<add name="ScriptsContext" connectionString="Data Source=SQLserverblah;Initial Catalog=blahdb;User ID=blah;Password=blah" providerName="System.Data.SqlClient" />
</connectionStrings>
Data project DbContext
public class ScriptsContext : DbContext
{
public DbSet<Question> Questions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ScriptsContext>(null);
modelBuilder.Entity<Question>().ToTable("Question", schemaName: "dbo");
}
}
The only config that is read is the config for the executing project. I.E. you are running the Web API website and it's config is used.
If you want Data project to be a black box, you will need to hard code the connection string or get it from a source other than configuration.
If you want to test this theory, you can remove the connection string from the Data project and still start Web API. The only reason you would need the connection string in the Data project is if you are using an ORM, like Entity Framework, that allows you to update the generated code files within Visual Studio.
Hope this helps.

How to use localDb with entity framework migrations?

I have Persistence class library, which contains my DbContext class. It also contains app.config file, where I have predefined connection string like this:
<connectionStrings>
<add name="<Namespace1>.Persistence.AssessmentContext" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\AssessmentContext.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Assuming that AssesmentContext has Namespace1.Persistence namespace.
When I try to enable-migrations using PM console, it gives me such an error:
An error occurred accessing the database. This usually means that the connection to the database failed. Check that the connection string is correct and that the appropriate DbContext constructor is being used to specify it or find it in the application's config file.
When I tried to debug it and put debug output into AssessmentContext ctor I found that the connection string is still using .\SQLEXPRESS data source.
Data Source=.\SQLEXPRESS;Initial Catalog=<Namespace1>.Persistence.AssessmentContext;Integrated Security=True;MultipleActiveResultSets=True
So what I am doing wrong? And why EF doesn't take my connection string from app.config?
The above connection string entry must be copied to the app.config of the executable program if you are using desktop app or copied to web.config if you are using web app.

EF 5 Migrations cannot connect to our database even though it does just fine at runtime

We have three projects.
Company.Domain (class library)
Company.PublicWebsite (MVC3 Web Application)
Company.InternalWebsite (MVC3 Web Application)
The two website projects have reference to Company.Domain.
Our EF 5 DbContext lives in Company.Domain.Data.EntityFramework and it looks like this:
using System.Data.Entity;
using Company.Domain.Data.EntityFramework.Entities;
namespace Company.Domain.Data.EntityFramework.
{
public class CompanyEntities : DbContext
{
public DbSet<Notification> Notifications { get; set; }
public DbSet<Report> Reports { get; set; }
public DbSet<ReportSection> ReportSections { get; set; }
public DbSet<ReportPage> ReportPages { get; set; }
// brevity brevity
}
}
We have enabled migrations and successfully used the tool in the past so I'm not sure why we are having issues now. Our migrations configuration lives in Company.Domain.Data.EntityFramework.Migrations and looks like this:
namespace Company.Domain.Data.EntityFramework.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using Company.Domain.Data.EntityFramework;
public class Configuration : DbMigrationsConfiguration<CompanyEntities>
{
public Configuration()
{
MigrationsDirectory = #"Data\EntityFramework\Migrations";
AutomaticMigrationsEnabled = false;
}
protected override void Seed(CompanyEntities context)
{
// empty at the moment
}
}
}
We then have an App.config file in the root of the Company.Domain project and it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="CompanyEntities" providerName="System.Data.SqlClient" connectionString="Data Source=devsql;Initial Catalog=CompanyEntities;uid=XXXXX;pwd=XXXXX;MultipleActiveResultSets=True;" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Our database lives on another server on the network. I'm able to connect to it in SQL Server Management Studio and our applications are able to connect at runtime just fine. However, when I try to run add-migration or even update-database I get the following error:
http://content.screencast.com/users/Chevex/folders/Snagit/media/80fbfd6a-4956-407f-b88f-d5a53a9e5feb/03.21.2013-10.25.png
System.Data.ProviderIncompatibleException: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. ---> System.Data.ProviderIncompatibleException: The provider did not return a ProviderManifestToken string. ---> System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
I've even reverted my changes to the model and then ran update-database just to see if it would say 'database is on latest migration' but I still got the above error. I've poured over the connection string in App.config over and over. I cannot figure out why migrations won't connect but both of our website projects work just fine at runtime. Migrations have worked in the past. Below are the migrations in solution explorer compared with those found in the __MigrationHistory table in the database.
http://content.screencast.com/users/Chevex/folders/Snagit/media/7abeaa46-ff0f-4817-a0d7-1adb086e8f0c/03.21.2013-10.30.png
http://content.screencast.com/users/Chevex/folders/Snagit/media/3c6ac54d-f63d-417f-9253-39b6a8fea85d/03.21.2013-10.32.png
It looks like I should be able to run update-database and have it tell me that it is up to date, but I get that error instead.
As I understand it, migrations shouldn't be paying any attention to our two website projects when I'm running migrations commands, but I poured over their Web.config files as well just in case. The connection strings are identical to App.config.
Edit:
I've even tried completely uninstalling and removing the EF 5 package from the projects and reinstalling. Same issue >:(
Did your start project contains web.config or app.config as EF use the start project as source of the connection string
OK, so that didn't work for me at first :(
Then after a cup of coffee and adding StartUPProjectName to it, it did!
Try:
Update-Database -StartUpProjectName MYPROJECT.NAME -Script
Try to point it to a start Up project where you web.config/app.config lives
If you get the help for enable migrations in the Package Manager Console
Get-Help enable-migrations -detailed
You can find this documentation for the -StartupProjectName option:
-StartUpProjectName
Specifies the configuration file to use for named connection strings. If
omitted, the specified project's configuration file is used.
The doc it's a little confusing, but it means that if you use this option to specify a project name, migrations will look for the connection string in the config file of the specified project. (The config file can be web.config or app.config).
If you're creating a web app, most probably the connection string will be in its web.config, so you have to specify the web app project. If it's other kind of project, the connection string will be in an app.config file of a class library or whatever, and you'll have to specify that project.
Besides it's recommended that you use a constructor for your DbContext class that specifies the name of the connection string, i.e.
public class CompanyEntities : DbContext
{
public CompanyEntities()
:base("ConnectionStringName")
{
...
}
....
}
In this way you don't depend on default connection strings, which may be confusing.
You say you can connect via SQL Management Studio, but my guess is you use Windows Authentication for that, and not the uid=XXXXX;pwd=XXXXX; supplied in your connection string.
Try to get Management Studio to connect using that userid and password.
Also, that account might be locked out (if it is an Active Directory account).
This sounds eerily like a problem a client of mine had. It had to do with something having mucked up the DbProviders section of machine.config. He put the details here: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/f2a19487-6d38-4a79-a809-d3efe4c9d9fe (it's the Adam Scholz answer to his boss' question. :) )
Julie
May be this is solved already but i got it solved by setting the start up project in my solution to the entity dll project ( having app.config file ). I did set the "Default project" in Package Manager Console window to the correct entity dll project but that did't work. For details
Entity Framework 6 with SQL Server 2012 gives System.Data.Entity.Core.ProviderIncompatibleException
system-data-entity-core-providerin
If your solution has multiple projects, try setting the Startup Project for the solution to the project that contains the Web.Config or App.Config file that contains the settings for EF.
I had a solution with a Web project and seperate project (Data.Models) for my models. All was well until I added a console application to the solution. As soon as I set that to be the startup project, EF Migrations would fail.
Also, if multiple projects in the solution have migrations enabled, always run the Update-Database on each project after you do a Add-Migration. My web project had a pending migration, and the migrations failed weirdly on the second project because of the pending migration in the first.

How to connect to the connection string written in the web.config of the web services

We have a web service project called 'Service' and in the web.config of the 'service' I have set the connection string as follows:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=L308;Initial Catalog=Dashboard;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I am trying to access the connection string from another project 'DBConnector' using the following code but getting null reference exception even though after adding the reference of the 'Service' into 'DBConnector'. using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
You will need to have the connection string in DBConnector project config file. Adding reference to a project doesn't bring in the config of that project in the main config of the project
If i got you
You can not do that if you want to use the Connection string of service in you library. You need to expose that as property or method
in you service.cs
public string connectionstring
{
get
{
return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
}
or
DBConnetor added as referance
If the DBconnector has added as referance in the Service layer than you can access it easily by the code you have written
If you need want to make that connection string Global so all you applications and services can use it you will need to put it in the machine.config.
The machine config if found here %WinDir%\Microsoft.NET\Framework\\CONFIG.
'Service' into 'DBConnector'.
Seems to be incorrect thing to do. It should have been other-way around!

Categories

Resources