SQL Server Express and Entity Framework - entity-framework

I'm new to SQL Server Express (not to SQL Server in general) and I have a problem. I'm using Entity Framework (6-beta) in an ASP.NET MVC application.
I created a database using the SQL Server Management Studio. I can connect to the DB using Management Studio and my local Windows user account.
I dind't change the default configuration, so the SQL Server stores the data files in :
C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA
The .mdf file of my database is stored in this folder.
My problem is: When I start the MVC application from Visual Studio, Entity Framework failes to open a connection to the database. The exception text is quite unprecise, but the inner exception reveals that it tries to connect to:
C:\Users\<MyUser>\Workspaces\<Solution>\<Project>\App_Data\<Context>.mdf
My connection string is:
"Data Source=.\SQLEXPRESS; Initial Catalog=<Name>; User Instance=False; Integrated Security=True;"
Does anyone know why Entity Framework tries to connect to this file? What can I do?

You need a web.config entry on the MVC application project (in case the DBContext is in another referenced project).
The web.config should have an entry like the one below in the connectionstrings section (note YOURCONTEXTNAME should match the name of your DBContext class).
<add name="YOURCONTEXTNAME" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YOURDATABASENAME;Integrated Security=SSPI"
providerName="System.Data.SqlClient" />

Ok. I found the problem. I edited the wrong web.config file by accident.
Asp.Net MVC 5 creates a second web.config file in the Views folder.
Of course, the connection string must be inserted in the web.config of the root folder.

Related

Connection strings adding namespace when deploying Entity Framework to Azure

I am deploying a site to Azure that uses EF6 using the VS Studio publish option.
I am using the default behavior for for database naming rather than specifying a connection string as I do development from multiple machines which have a mixture of localDB or SQL Express:
public WebsiteDBContext() : base("WebsiteDBContext")
The EF code is all in a separate project to the website as it is used on multiple websites sharing the same DB.
When I publish to Azure the connection strings added to web.config include a namespace from the project the DBContext code is in:
<add name="Utils.Models.WebsiteDBContext" connectionString="Data Source=****.database.windows.net;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=****;Password=****" providerName="System.Data.SqlClient" />
<add name="DefaultConnection" connectionString="Data Source=tcp:****.database.windows.net,1433;Initial Catalog=CreweAllen;User ID=****;Password=****" providerName="System.Data.SqlClient" />
<add name="Utils.Models.WebsiteDBContext_DatabasePublish" connectionString="Data Source=****.database.windows.net;Initial Catalog=MyDatabase;Persist Security Info=True;User ID=****;Password=****" providerName="System.Data.SqlClient" />
The Migration fails to run I think because it can't find the database.
If I manually create the tables and remove the migration table creations the website fails with: 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. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation.
But if edit the web.config and remove "Utils.Models." from the WebsiteDBContext connection string but not the WebsiteDBContext_DatabasePublish it connects to the database ok.
How can I get the connections correctly named and the migration to run? Have tried hard but failed to find a solution.
Thanks
Eventually resolved it.
The published application couldn't find a connection string with the name it was looking for "WebsiteDBContext" as the VS deployment wizard was naming the connection string "Utils.Models.WebsiteDBContext" so it was falling back to the default EF connection which was localDB:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
When I stopped explicitly naming the DB name in the DBContext:
public WebsiteDBContext() : base()
Then the name of the connection the app looked for was "Utils.Models.WebsiteDBContext" which it found.
So what doesn't work well is publishing to Azure through the VS wizard with named DBContext as the connection strings created on Azure have the full namespace.
Your context class is named WebsiteDBContext. By convention, you'll have a connection string in your web.config named WebsiteDBContext. When you enable code migrations via this wizard, the wizard will create a second connection string named WebsiteDBContext_DatabasePublish that will only be used for running your code first migrations.
Update your DbContext which the datapublish stuff is still in the webconfig but no I'm no longer getting the exception.
public WebsiteDBContext():base("WebsiteDBContext", throwIfV1Schema: false) // throwIfV1Schema:false was added as the Identity V2 was causing an error in Azure
For more details you could refer to this issue.

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.

Entity frawork not work with azure db on azure website, but localy yes

I have problem with Entity framework. If I start web app localy thats all is right, but if I publish on azure then database not work. Localy I use same connection string to azure db, I do not have local database. Where can be problem?
<connectionStrings>
<add name="AzureDbConnectionString"
connectionString="Server=serverName.database.windows.net,1433;Database=UserName;User ID=UserName#serverName;Password=SuperPassword;Trusted_Connection=False;Encrypt=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Error: Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file. See http://go.microsoft.com/fwlink/?LinkId=260882 for more information.
Peter
On the Azure portal, go to websites -> your website -> configure. Scroll down to "connection strings" and add your connection string there. Make sure you give it the same name as in your web.config file, (in your case "AzureDbConnectionString")

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.

where does Entity Framework keeps it's data by default?

I'm using Code-first and entity framework in my .NET MVC 3 application, I created simple entity and can save new one and retreive list of them from entity framework. The problem is that I can not find the db where this data is stored.
I created another application, copied my entity class there and it uses the same storage as the first one, I see the list of entities which were added in the first app.
There is only one connection string in web.config (for default membership provider).
Where is the entity framework data? how can I use my database for it?
Thanks
Ok, I found where the DB is, in my case it is in c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\DATA\
in order to use my database I use this connection string:
<connectionStrings>
<add name="MyEntities"
connectionString="data source=.;
Initial Catalog=DbName;
Persist Security Info=True;
User ID=user;
Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I'ts a pity it can not use the same DB as membership provider, it has to be another database.