EF5 Code First Migration problems publishing to IIS - entity-framework

I've created a MVC 4 project which uses EF5 Code First with migrations.
Because I was new to this topic I used the following article.
Now that the development is finished I want to publish to IIS (I use FTP or Web deployment package). So before publishing I changed the connectionstring to the right db server.
But after publishing the site I get an exception when accessing pages which make use of the DB. The exceptions refers to the fact that he can't connect to the database.
Because of these problems I decided to try it out locally on another DB server than the default one "(LocalDB)\v11.0". BTW: "(LocalDB)\v11.0" works like a charm...
While debugging I got a better look at the error.
Here is an image of the error:
What I've already tried:
Generate a sql script by executing "Update-Database -Script
-SourceMigration:$InitialDatabase" in the Package manager console. After I ran this script on the dbserver to create the db. Tables were
created but the error was still there.
I changed my connectionstring to all kinds of combination with no
results
I already used a custom user for the app pool in ISS and gave this user full rights to the DB server and the db.
Here is the most important part of my web.config:
<connectionStrings>
<add name="DefaultConnection" providerName="System.Data.SqlClient" connectionString="Data Source=LOCALHOST\MSSQLSERVER;Initial Catalog=ProjectX;Integrated Security=TRUE;MultipleActiveResultSets=True" />
</connectionStrings>
And
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
<parameters>
<parameter value="Data Source=LOCALHOST\MSSQLSERVER; Integrated Security=True; MultipleActiveResultSets=True" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
My DBCcontext class constructor looks like
public DBContext(): base("DefaultConnection")
{
}
I guess I am missing something, this is the first time I use EF Code First with migrations.
This problem is really driving me crazy. I am out of ideas.

Just found out that the problem was caused by the connectionstring.
The string was incorrect, seems like you if you have a default SQL Server you just need to use
"Data Source=LOCALHOST".
I guess because of all the problems I had that day with the deployment i overlooked the easy parts. Yust make sure you the following things are true when you have problems like I did:
Your connectionstring has the same name as your DBContext. Another sollution could be to do like i did and add the connectionstring name to the base:
public DBContext(): base("DefaultConnection")
{
}
If you also have the defaultconnectionfactory set. Make sure to also update the Data Source there. This was one of the problems I struggled with. I didn't check the bottom of my web.config ...
If the problem still persists you can use EF profiler to have a look at the connectionstring when your app of site is accessing the DB.

Related

connectionString defaulting to production database.. Entity Framework

I am learning asp.net mvc 4 on top of entity framework. There is a project at work I took over and I am trying to centralize the connection credentials depending on the environment (dev, test, prod) the application is in.
Currently I have the connectionstring dynamic, but for some reason entity framework ignores the connection string initial Catalog setting.
<connectionStrings>
<add name="name1" connectionString="metadata=res://*/Model.csdl|res: //*/Model.ssdl|res://*/Model.msl;provider=System.Data.SqlClient;provider connection string="Data Source=001\;Initial Catalog=**;Integrated Security=False;User ID=**;Password=**;MultipleActiveResultSets=True;Application Name=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="name2" connectionString="metadata=res://*/Entites.csdl|res://*/Entites.ssdl|res://*/Entites.msl;provider=System.Data.SqlClient;provider connection string="data source=001\;Persist Security Info=True;User ID=**;password=**;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I have no idea what half of the stuff in the connectionString means, but it is the second connection string giving me troubles, "name2"
Running the debugger shows the base class that extends the ObjectContext called like so,
: base("name=name2", "name2")
I figured Initial Catalog was already set in the connectionstring, "name1" and that would transfer to the name2.. but for the heck of it I added the Initial Catalog to the second connection string and it still defaults to the wrong catalog. I am connecting to the same database server but we have a test and a production database..
What could be overriding this catalog setting and redirecting to the wrong database? When I run my code, I get an innerexception telling me the username (the test database username) doesn't have access to the production database, but I am not sure why the production database is being passed in.
Here is the exception:
The server principal "testuser" is not able to access the database "ProductionName" under the current security context.]
initializing ObjectContext
public Entities() : base("name=name2", "name2")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
This is also in the web.config files:
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
Something else interesting I noticed. When I leave the Initial Catalog setting in on the "name2" connectionstring, and set to the test database, and all the credentials are correct, I get the original error as I posted. If I change the initial Catalog to the production name and leave the wrong credentials to log in, I get a log in failed error. Same if I change the credentials around and leave the test database in for the initial catalog. So it seems it's authenticating properly, but something else is a factor once the connection goes through?
For anyone else who stumbles across this problem. I finally figured it out. The other developer was referring to the production database explicitly in all of the stored procedures. I took out all the references and left the implicit call using the "use" statement that was injected implicitly during the export/import process..
Example:
USE [TestDatabase] <---- this goes at top of procedure
Here was an explicit call to the production database:
FROM [productionDB].[dbo].[Table] table
just make it an implicit call like so:
FROM [dbo].[Table] table
If my solution is not the answer for you, I also stumbled across this bug in sql server 2008:
https://connect.microsoft.com/SQLServer/feedback/details/354291/the-server-principal-is-not-able-to-access-the-database-under-the-current-security-context-microsoft-sql-server-error-916

Use Entity Framework Code first with any database

I use SQL Server developer edition and would like to use EF code first. I found many articles explaining how to work with either a localdb or SQLExpress. How do I tell my project to rather use my ..\SQL2008 instance?
I'm thinking that somewhere, somehow, one must be able to tell the project to use a specific connectionstring. But where? Adding it to my app.config file doesn't work. This is what I've tried:
<connectionStrings>
<add name="Context" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TimeApp;Data Source=Amanda-PC\SQL2008; MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
You can specify which connection string to use by passing the name of the connection string to the DbContext.
public class YourContext : DbContext
{
public YourContext()
: base("Context")
{
}
}
See this for more information

Change default location of LocalDb

I am programming with EF5-code first and want to use LocalDb. How can I change the default location of LocalDb database file? Default location is %USERPROFILE% directory according to http://blogs.msdn.com/b/sqlexpress/archive/2011/10/28/localdb-where-is-my-database.aspx
Previously I was using SqlCe DbConnectionFactory which accepts a parameter for database path/name. If I use AttachDbFileName parameter then it raises an exception if database doesn't exist (it's supposed to create it!).
I got this working thanks to this post. The answer is simple. Basically I added
<connectionStrings>
<add name="DataModel.Context" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=database;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\database.mdf" providerName="System.Data.SqlClient" />
to the configuration section of app.config and it magically replaced the "database" with my actuall database (DbContext) name. EF code first also works perfectly to create the database if it doesn't exist.

Entity Framework DbContext Connection string in app.config/web.config not being seen

So, I have followed this instruction from ADO.NET team blog to try to make a small test project.
I have double-checked everything. It doesn't seem to work and keeps saying connection string is missing.
http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-model-amp-database-first-walkthrough.aspx
Step. 1
Build this UserModels.dll. In the dll, App.Config file, edmx generated this connection string: (hit the 'test' button when making it, and it connects successfully, and generated the edmx diagram of all the tables from 'UserDatabase')
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="UserModelsContainer" connectionString="metadata=res://*/UserModels.csdl|res://*/UserModels.ssdl|res://*/UserModels.msl;provider=System.Data.SqlClient;provider connection string="data source=MyDesktop\SQL2008;initial catalog=UserDatabase;integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Step 2.
Then I made a test project:
class UnitTetst1 ....
TestMethod1()....
using (var db = new UserModelsContainer()) {
int i = db.Users.Count(); // <---expecting '0' for a new db, but I get an exception
}
---------PROBLEM HERE -----------------
Step 3. Run the test. Then I get an error InvalidOperationException like this:
"No connection string named 'UserModelsContainer' could be found in the application config file."
Seems like DbContext doesn't know where to pick up the connectionStrings from App.Config??
Please help~~
When running a program, it's the app.config of the .exe file being run that is read. The app.config of the .dll is never used. Since UserModel.dll is a dll, there must be an .exe (or web site) somewhere that you run. Place the connection string in that exe's app.config (or if it is a web site in the web.config).
I had this issue when I was attempting to do an update-database command from the "package manger console". I had a separate project for my code first Data access layer and another for my web project, etc
I was using the following command: "update-database -projectname MYPROJECTDANAME -CONNECTIONSTRINGNAME CONNECTIONSTRING -Force"
so it pointed at my MYPROJECTDANAME project however it takes the connectionstring name from startup project you have specified. Therefore make sure the project you have marked as the startup project has the required connection string.

Setup of mvc-mini-profiler for EF-db- first

I'm trying to use the mini-profiler with old-style EF code - database-first.
So far:
I've created a db context using:
string connectionString = GetConnectionString();
var connection = new EntityConnection(connectionString);
var profiledConnection = ProfiledDbConnection.Get(connection);
_context = profiledConnection.CreateObjectContext<MyEntitiesType>();
but then I hit a "Unable to find the requested .Net Framework Data Provider. It may not be installed."
which I worked around using a <system.data> reference to the MvcMiniProfiler provider:
<system.data>
<DbProviderFactories>
<remove invariant="MvcMiniProfiler.Data.ProfiledDbProvider" />
<add name="MvcMiniProfiler.Data.ProfiledDbProvider" invariant="MvcMiniProfiler.Data.ProfiledDbProvider" description="MvcMiniProfiler.Data.ProfiledDbProvider" type="MvcMiniProfiler.Data.ProfiledDbProviderFactory, MvcMiniProfiler" />
</DbProviderFactories>
</system.data>
but now I'm hitting a stack overflow somewhere in C:\Users\sam\Desktop\mvc-mini-profiler\MvcMiniProfiler\Data\ProfiledDbProviderServices.cs. Looking at the latest source I'm wondering if I've somehow got the setup wrong for this - if somehow my profiled connection is containing another profiled connection is containing....
Any help/advice?
Update - looking at http://code.google.com/p/mvc-mini-profiler/wiki/FrequentlyAskedQuestions at least one other person has seen the same sort of problem with 1.7 - although (s)he's doing code first. I'll keep playing to see if I can work out what to do...
Try 1.9. With the update, I just added the new Initialize method in Application_Start and removed the DbProviderFactories config section and now I have SQL profiling with EF (2 databases even, one with code first and one with database first).
protected void Application_Start()
{
....other code
MiniProfilerEF.Initialize();
}