Database Connection Error with ef-code-first - entity-framework

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"
...

Related

Azure Deployment Entity Framework Connection String Keyword not supported: 'metadata'

I have been developing an application locally using asp and entity framework to interact with my database. I am using a model first approach. I want to deploy this app to Azure but I keep getting the error "Keyword not supported: 'metadata'."
Through searching and reading posts like this: Windows Azure, Entity Framework. Keyword not supported: 'metadata'.
I know its an issue with my connection strings but i can't figure out what i'm doing wrong.
Connection string in my local web config:
<add name="BeCivicData" connectionString="metadata=res://*/Models.BeCivicData.csdl|res://*/Models.BeCivicData.ssdl|res://*/Models.BeCivicData.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=BeCivic;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" /></connectionStrings>
Generated Connection String for the Azure DB:
Server=tcp:becivicserver.database.windows.net,1433;Initial Catalog=BeCivic;Persist Security Info=False;User ID={MyID};Password={MyPass}5;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;
On the Azure Applications settings page i have defined my connection string as both of the above which didnt work so i tried combining them to have the EF meta data (below) but the Azure connection string and that also gave me the Meta Data error:
metadata=res://*/Models.BeCivicData.csdl|res://*/Models.BeCivicData.ssdl|res://*/Models.BeCivicData.msl;provider=System.Data.SqlClient;provider connection string="Server=tcp:becivicserver.database.windows.net,1433;Initial Catalog=BeCivic;Persist Security Info=False;User ID={myid};Password={mypass}5;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" " providerName="System.Data.EntityClient"
In my application the EF .edmx file is in a folder named Models.
Both the database element and the code elements deployed separately to azure successfully and now i just need to link them up.
Keyword Not Supported:metadata
When you attempt to use the the connectionstring within the Azure Portal Connection Strings setting, it will get the above error.
So, try to change the type from SQLAzure to Custom.
You could refer to this article to troubleshoot.
To avoid parsing the connection string yourself, you can use the EntityConnectionStringBuilder class the parse the string and retrieve the database connection string from its ProviderConnectionString property.

DB First, MVC 4, CREATE DATABASE permission denied in database 'master'

I keep getting this error on my server when I publish my site - even without changes in database model.
The site is running fine local.
I'm using the DB first approach.
If I delete all files in the site on the server, restore my local database on the server. Publish the site from VS. Sometime it will run fine after that.
If I then make a few changes in the database CONTENT I will get the error.
I don't whant to create any database/tables on the server - just disable the part of the code, that need to do it. In MVC3 we had this DropCreateDatabaseIfModelChanges but I can't see any of that in my current site.
What can I do?
My connectionstring:
<connectionStrings>
<add name="GoBagHomeComEntities" connectionString="metadata=res://*/Models.GoBagHomeModel.csdl|res://*/Models.GoBagHomeModel.ssdl|res://*/Models.GoBagHomeModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\sqlexpress;initial catalog=GoBagHomeCom;Persist Security Info=True;User ID=xx;Password=xxxx;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
And my dbcontext
public partial class GoBagHomeComEntities : DbContext
{
public GoBagHomeComEntities()
: base("name=GoBagHomeComEntities")
{
}
Check dbo.__MigrationHistory if you have records means EF is trying to migrate, so truncate the table and try it again.
if the same thing repeated so you might need to check EF weather it migrates as settings.
have a look to this answer this, you need to have the connection string in web.config file, I think this is the only missed thing.
It seems like the problem is solved :)
I'm sure Owin was the bad guy - I was only using it for creating the authentication cookie. Nothing about tables.
After remove all Owin related code on the site it's running.
If your bring any change in your database you should follow the following steps:
Update the .edmx file. To update it double click on .edmx when it will open, please right click on a blank space of this file and select "update model from database".
Save and close the file.
Build the project.
Copy .dll file from bin folder and past it where you have hosted your application.

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.

Entity Framework Cannot find connection string

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>

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.