ASP.NET MVC 4 EF6 cannot connect to SQL Server Express database - c#

I have a weird error when I move to SQL Server Express from LocalDb. This is the error:
This operation requires a connection to the 'master' database. Unable
to create a connection to the 'master' database because the original
database connection has been opened and credentials have been removed
from the connection string. Supply an unopened connection.
This error occurs when I tried to CreateDatabaseIfNotExists on context initialization.
Here is my connection string:
<add name="DefaultConnection"
connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AlvinCMS;MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient" />
Here is my context:
public class AlvinCMSMigrationDBContext : DbContext
{
public AlvinCMSMigrationDBContext() : base("DefaultConnection")
{
Database.SetInitializer<AlvinCMSMigrationDBContext>(new CreateDatabaseIfNotExists<AlvinCMSMigrationDBContext>());
}
I initiate the database on the global.asax:
protected void Application_Start()
{
//Check And Init Database
Alvin_CMS.App_Start.DatabaseConfig.Initialize();
And finally this is my initialization code:
public static void Initialize()
{
Alvin_CMS.Models.AlvinCMSMigrationDBContext migrationDB = new Models.AlvinCMSMigrationDBContext();
try
{
if (!migrationDB.Database.Exists())
{
migrationDB.Database.Initialize(false); //ERROR HERE!
AlvinCMSExtension.Models.AccountDBContext accountDB = new AlvinCMSExtension.Models.AccountDBContext();
accountDB.Database.Initialize(false);
SetDefaultValue(migrationDB);
}
migrationDB.Database.Initialize(false);
}
catch (Exception e)
{
migrationDB.Database.Delete();
AlvinCMSExtension.Helper.Log(e);
}
}
I do not know what is wrong with my code, because it was fine when I use LocalDb, but now I cannot even connect to my database.
Here are my attempts to fix this issue:
I put Persist Security Info = True;Trusted_Connection=False; - still producing the same error.
I tried to change Database.SetInitializer<AlvinCMSMigrationDBContext>(null); But I need to create the database if not exist, so this is not a fix for me

You can use connection string as shown below.
<add name="DefaultConnection" connectionString="Server=localhost; Database=
AlvinCMS;Trusted_Connection=True;" providerName="System.Data.SqlClient" />

In my case "StoreMan" is the database name. Replace it with your own.
<add name="StoreMan" providerName="System.Data.SqlClient" connectionString="Server=localhost; Database=StoreMan;Trusted_Connection=True;Integrated Security=True;MultipleActiveResultSets=True"/>

Related

EF code first database: login failed for same user for one of two databases, equivalent connection string

I'm trying to create two databases with SQL Server 2014, Entity Framework. One is created "automatically" with asp.net identity and the other one I create using a seed method in Configuration.cs.
Both have the same SQL login in the connection string, but only the identity database is created. For the other one, the following error occurs:
The underlying provider failed on Open. [...]
System.Data.SqlClient.SqlException: Cannot open database "dbname" requested by the login. The login failed.
Here are the connection strings:
<connectionStrings>
<add name="AntContext"
connectionString="Database=dbname;User Id=user; Password=mypw;"
providerName="System.Data.SqlClient" />
<add name="DefaultConnection"
connectionString="Database=dbnameidentity;User Id=user; Password=mypw;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Checking in SQL Server Management Studio, the database dbnameidentity is created and even populated with seeding data from Configuration.cs, but for the other one the login fails.
I have no idea why this happens. I'll provide more information if necessary. Thanks.
Here's the head of my seed method.
protected override void Seed(IdentityDbContext context)
{
var antcontext = new DataContext.AntContext();
If you don't have an initialiser set for your context. This means it will not try to create the database. If you want to ensure the DB is created, then you can use the CreateDatabaseIfNotExists initialiser, for example:
public class AntContext: DbContext
{
public AntContext(): base("AntContext")
{
Database.SetInitializer<AntContext>(new CreateDatabaseIfNotExists<AntContext>());
}
//snip
}

How to set the database name in the connection string with Entity Framework 5

So I have Solution with two projects. The first projects should act as a Data Access Layer so there in the app.config file I have this:
<connectionStrings>
<add name="BloggingContextCF"
connectionString="provider=System.Data.SqlClient;
provider connection string="
data source=*****\SQLEXPRESS;
initial catalog=CodeFirst.Blogging;
integrated security=True;
MultipleActiveResultSets=True;
App=EntityFramework""
providerName="System.Data.EntityClient" />
The second Project is a ASP.NET Web Forms project, where I removed the default connection string pointing to the (local) instance leaveing only one connection string, the one from the first Data Access Layer project. Which actually works and the database is created on my SQL 2008 R2 server, but instead of the desired (and expected) database name - CodeFirst.Blogging the name is DataAccessLayer.BloggingContextCF where DataAccessLayer is the name of the project and BloggingContextCF is the class extending DbContext.
What I need to change in my connection string so I can get the desired name?
Try
public BloggingContextCF ():base("CodeFirst.Blogging") {}
make the connections string like
Point it to sql client
providerName="System.Data.EntityClient"
to
providerName="System.Data.SqlClient"
For full connection string do it like
<add name="BloggingContextCF" connectionString="Server=YOUR_SERVER;Database=DATABASE_NAME;User ID=USER_ID;Password=PASSWORD;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.SqlClient" />
For more connectionstring example follow the link
and don't forget to modify your dbcontext
public class YourContext : DbContext
{
public UsersContext()
: base("BloggingContextCF"){ }
}

Get data from local DB not working

I have create MVC5 application and I have local DB ,currently I have entered data
to the table and I able to see that in the MDF file under server explorer ->data connections ,now I want to read it via API below and its not working i've provided the ID which I have in the table and I get null ,I think maybe that I need to provide the connection string to the API but not sure how ,any idea how to do that?
This is DB context from the model definition
public class PersonModelDbContext : DbContext
{
public PersonModelDbContext()
: base("Connection1")
{
}
This is the read API
private PersonModelDbContext db = new PersonModelDbContext();
public Person GetPrviderData(string id)
{
Person person = db.Person.Find(id);
return person;
}
This is the connection string in the WEB CONFIG FILE
<connectionStrings>
<add name="Connection1" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Person.mdf;Initial Catalog=Persons;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
Update - in addition I try with the following without success ,I got error:
db.Database.Connection.ConnectionString = #"Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Person.mdf;Initial Catalog=Persons;Integrated Security=True";
An exception of type 'System.Data.DataException' occurred in
EntityFramework.dll but was not handled in user code
Additional information: An exception occurred while initializing the
database. See the InnerException for details.
You could try setting your connection string to more this format since it is local
<add name="DataBaseConnectionName"
connectionString="Data Source=[ServerNameHere];User ID=[DatabaseLogonID/Probably sa];Password=[DatabasePassword];Initial Catalog=TheNameoftheLocalDB;"
providerName="System.Data.SqlClient" />
You could try that to establish a connection also don't keep the [brackets] in the connection string.

Remove ConnectionString from Web.config using Entity Framework CodeFirst

Transform web.config won't work well for Entity Framework CodeFirst because the connection string is added dynamically after transform when publishing. We have a dynamic connection settings being set in code for CodeFirst when releasing to different environments.
I have tried the correct removal method but the published results ends up with the connection string in the web.config.
Are there any work arounds for this? Putting connection info in our web.configs isn't an option. Adding the connection info dynamically at runtime works well.
The problem is when publish adds the connection info in the web.config the app gets a 500 error because codefirst is attempting to use an invalid connection string for the environment that is not sandbox where it was created.
We are changing that at runtime here and that is working.
public MyAppDataContext()
{
this.Database.Connection.ConnectionString = OurDynamicConfigSettings.GetSetting("MyAppConnectionString");
}
The codefirst though is attempting to use what is in web.config before we set it dynamically. The fix is to remove the connection info from the web.config.
It all works except when building on build server or publishing, codefirst inserts the connection info back into the web.config every time we publish. Having to remember to remove this each time is not good practice and prone to errors if you forget.
Code for removing connection string in our transform file should work but doesn’t.
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="XPath(configuration/connectionStrings[#name='MyAppConnectionString'])" />
</connectionStrings>
Your transform should be:
<connectionStrings>
<add xdt:Transform="Remove" xdt:Locator="Match(name)" name="MyAppConnectionString" />
</connectionStrings>
But, I have to ask.. are connection strings stored in your database or something? Why do you need to do them in code?
You could just do this:
public class MyDataContext : DbContext {
public MyDataContext(string connectionString) : base(connectionString)
...
}
Then when you create you contexts, you do this:
using(var context =
new MyDataContext(OurDynamicConfigSettings.GetSetting("MyAppConnectionString"))) {
...
}
public partial class MyContextEntities : DbContext
{
public MyContextEntities(string ConnectionString="[Your Entity Connection String Here]")
: base(ConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Replace " with ' (single quote) in connection string

DbContext behave differently within different classes

I have a local ASP.NET MVC 3 Windows Azure Project where I use a local instance of MSSQL Express for my emulator.
In my web.config I have the following connection string:
<add name="ExampleDb" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=ExampleDb;User Instance=true;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
For debugging purposes I have the following in my WebRole.cs file:
public override bool OnStart()
{
ExampleDb context = new ExampleDb();
context.ExampleItemEntries.Add(new ExampleItem() { ExampleItemId = 1, Att1 = "1", Att2 = "2" });
context.SaveChanges();
return base.OnStart();
}
When I perform this action I can actually see the content in my code-first generated database (using Entity Framework). Database: ExampleDb, Table: ExampleItem.
However, doing the exact same thing in ExampleController does NOT update the database. Instead this data goes somewhere else (I have no idea where). When I visit my controller via the browser I can upload data and look at it but it is not stored in my ExampleDb database, only data sent from WebRole.cs is in the database.
Any ideas what's causing this behaviour?
ExampleDb.cs looks like this:
public class ExampleDb : DbContext
{
public ExampleDb() : base("ExampleDb") { }
public DbSet<ExampleItem> ExampleItemEntries { get; set; }
}
Your connection string contains 'User Instance=True'. This means that SQLEXPRESS uses a user instance to store your data. This is a completely different instance of SQL Server that contains a new set of databases.
I assume the code in WebRole.cs is run in a different user account than the code in ExampleController. When the ExampleController is run under a user account that is not an administrator, a user instance is used...
So when you remove 'User Instance=True' from your connectionstring and assign the proper access rights to your SQLEXPRESS database instance, that would solve the problem.
In CodeFirst Model you should define the connection string in the web.config first as below:
<connectionStrings>
<add name="ExampleDbConnection"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;
database=ExampleDb;
AttachDBFilename=|YouDataDirectory|yourdb.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
<connectionStrings/>
The DbContext class constructor accepts a name-value pair specifiying connection-string name in web.config. So you can reference this connection string in your context:
class ExampleDb : DbContext
{
public ExampleDb() : base("name=ExampleDbConnection") { }
...
}
This code does work fine in a ASP.NET MVC Web Role so you can try as above.

Categories