Changing ConnectionString authorization method cause migration fail - c#

I've created project to read from MSSQL DB and display some data. VS's wizards created connection string like the following:
<add name="SomeContext" connectionString="data source=xxx.xxx.xxx.xxx\_name,port;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
When I tried to deploy application to the real web server I changed connection string to use faceless DB account:
<add name="SomeContext" connectionString="data source=xxx.xxx.xxx.xxx\_name,port;User Id=userid;Password=password; MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />
It looks like EF thinks that there some migration needed and tries to execute a lot of meaningless operations including attempts to execute SQL expressions with schema creating.
I have no write permissions on this DB server and I don't see any reasons to allow EF change DB structure.
So I'm completely lost there. What is the proper way to change authorization methods without changing on DB side?

Try to change connection string to production in VS project, then use Update-Database via Package Manager Console.

Pretty strange for me but the root of the issue was in default "initial catalog". It was stored somewhere for connection with integrated security but when I changed authorization method default was broken. As soon I defined initial catalog it was fixed.

Related

Get Azure connection string in datalayer

Someone thought, a long time ago, it was a good idea to add connections string hardcoded in the datalayer of our web api. Because of this legacy I cannot remove this class. This class inherits IDbContextFactory and it needs to retrieve a connection string, which now is hard coded. To make it more... dynamic, I want to use the Azure connection strings for this.
1 I added the connection string to the configuration of the app service
2 According to a lot of websites I can just add the following code to retrieve the connection string:
connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
This does not work; it gives a "Object reference not set to an instance of an object." error.
Other say you need to add a prefix and the environment:
connectionString = Environment.GetEnvironmentVariable("SQLCONNSTR_DefaultConnection");
This does not work either, obviously. And yes, I selected sql server in the dropdown.
Other thing I tried, as someone suggested, is to add the connection string to the web.config. And again; this didn't work.
Good to know is that this is .NET 4.6.2, so all the beautiful solutions for .NET Core 1/2 aren't going to work.
First you have to include the same connection string in the web.config with empty connectionString value. Then you can overwrite from the application settings section.
`<connectionStrings>
<add name="DefaultConnection" connectionString="" />
<add name="CMSEntities" connectionString=""
providerName="System.Data.EntityClient" />
</connectionStrings>`
For entity framework specify providerName as "System.Data.EntityClient" and settings chose Custom instead of SqlServer

Entity Framework MigrateDatabaseToLatestVersion CREATE DATABASE permission denied in database 'master' error

I've been looking through questions on here but have yet to come across anything that deals with my problem, apologies if this is a duplicate and I've missed something.
I have an ASP.Net MVC project with Entity Framework Code First.
In my Dbcontext I have;
public Context() : base("DatabaseName")
{
System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<Context, Configuration>());
}
In my web config I have;
<connectionStrings>
<add name="DatabaseName" connectionString="connsection string is here"/>
</connectionStrings>
When my application is deployed, I get the error
'CREATE DATABASE permission denied in database 'master'.' as soon as
it tries to access the Context for the first time.
What I don't understand is how to stop it trying to create a database and just use the connection string that I have given it. The database already exists (It's on shared hosting so I don't have much control over it) and I know the connection string is correct as I have Hangfire installed in the same application, using the same connection string and it has successfully created the tables but for some reason EF doesn't create the tables in the database and instead tries to create one, which it cannot do.
Entity Framework is installed in the same project as the config file, in fact, it's a single project application.
I've tried creating another database and adding a second connection string in case Hangfire was preventing EF from using it but had the same issue. I've also tried putting the full connection string directly into :base("") on the context, but it has no effect.
try getting connectionString by name
public Context()
:base("name=DbConnection")
{
}
in Web.config file add
<connectionStrings>
<add name="DbConnection" connectionString="Data Source=serveraddress;Persist Security Info=False;User ID=usename;Password=pass;Initial Catalog=databasename" providerName="System.Data.SqlClient" />
</connectionStrings>

SQL Connection String in MVC Application

Im working on a MVC Application and so far ive been using localDB since that was which was included in the tutorial. I want to switch the application now to my SQL Server but im not sure how to.
I get that I have to change the connection String. But not in what way exactly since the SQL Server has a username and password which my localDB doesnt.
Another question regarding this is, do I have to create the tables myself in the beginning on the SQL Server or will they be generated by the entity framework like in my localDB?
Current connection string for localDB:
<add name="AcquisitionDBContext"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Acquisitions.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
Im pretty new to this so any help is very much appreciated
if you are going to use MS SQL then it wil look something like this:
<add name="AcquisitionDBContext" connectionString="Data Source=hostname\sql_instance_name;Initial Catalog=databaseName;Persist Security Info=True;User ID=username;Password=password;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
Where "hostname\sql_instance_name" is the servername(or ip)/the sql instance name eg. localhost\sqlexpress
ConnectionStrings.com is the best reference for connection-string syntax. It shows you the options to use when you have a username+password. In this case:
Server=myServerAddress; Database=myDataBase; User Id=myUsername; Password=myPassword;
Entity Framework will not create your tables for you unless you tell it to by calling something like this:
Database.SetInitializer( new DropCreateDatabaseIfModelChanges<YourDbContextHere>() );
(Where Database is the System.Data.Entity.Database type).
Try it:
<connectionStrings>
<add name="<<Name of Connection String>>" connectionString="Data Source=<<Put here path to your SQL SErver>>;Initial Catalog=<<Database name>> ;Integrated Security=SSPI;Trusted_Connection=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
Here's how connection string should look like (tweak to your needs)
<add name="DefaultConnection" connectionString="Data Source=server_name,port; Initial Catalog=your_catalogue_name; Integrated Security=False; User ID=userName;Password=Passwd; MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
Before first run I would recommend using migrations.
Go to PackageManagerConsole (if you don't have it in menu, install NuGet first via Extension and Updates)
Then inside console type Enable-Migrations (if you didn't already).
Next type Add-Migration your_migration_name and then Update-Database to let migrations create tables for you.
If you change something in your model files later, you can again type Add-Migration your_migration_name and Update-Database to update database with those changes.

Azure Publish Database First Connection String Not Working

I have gone through the steps to publish my web app using database first on the azure portal.
However, when I publish I get this error message:
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.
My connection string in the web.config after it has been modified by publish:
<add name="MySiteEntities" connectionString="metadata=res://*/MySite.csdl|res://*/MySite.ssdl|res://*/MySite.msl;provider=System.Data.SqlClient;provider connection string="data source=tcp:**********.database.windows.net,****;initial catalog=MySite;user id=username#**********;password=*******;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
My context (generated by edmx):
public partial class MySiteEntities : DbContext
{
public MySiteEntities()
: base("name=MySiteEntities")
{
}
...
I am very confused becuase it seems like entity framework is trying to use code first rather than database first.
UPDATE:
I just tried using the same connection string locally and the web app seems to run fine. The web app does connect to the remote database fine. It is only when I publish to azure it fails.
Read my answer to a similar question at Entity framework work locally but not on azure.
If you made the same "mistake" I did, this is what's happening ... the Azure-deployed app isn't finding your connection string "MySiteEntities" inside your web.config. Instead, at the time your created your Azure Web Site (or Cloud Service or whatever), you created an associated Azure SQL Database and gave its connection string the exact same name, "MySiteEntities". This latter connection string is a "plain" connection string without Model/Database-first metadata references, and so is being treated as a Code-First connection by EF, which then complains about the conflict. See Code First vs. Database First for an explanation of this distinction.
It should be:
<connectionStrings>
<add name="MyDatabaseModelEntities"
connectionString="metadata=res://*/MyDBModel.csdl|res://*/MyDBModel.ssdl|res://*/MyDBModel.msl;
provider=System.Data.SqlClient;
provider connection string="
Data Source=<provideServerName>.database.windows.net;
Initial Catalog=MyDatabase;
Integrated Security=False;
User ID=<provideUserID>;
Password=providePassword>;
MultipleActiveResultSets=True;
Encrypt=True;
TrustServerCertificate=False""
providerName="System.Data.EntityClient"/>
</connectionStrings>
I changed connection string to remote (Azure) on my local web.config, then remove all set connection strings during publishing and publish web.config. It rewrites remove web.config. Then return connection string on local web.config to local connection. It works fine now.

How do I store users in my SQLEXPRESS database in C# MVC?

I am just learning MVC and I wanted to store my data in SQLEXPRESS instead of the MDF file that's provided.
I went online and learned that I was supposed to change Web.config, so I commented out and replaced the connection string like so:
<connectionStrings>
<!--<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />-->
<add name="ApplicationServices"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=BuySellDB"/>
</connectionStrings>
I was hoping that System.Security.Membership would automatically create a new database and table to hold my information, but it doesn't -- instead, it just barfs because it can't find a database there. How do I configure it to create a new database and table if none exists?
Edit: I was watching tutorial videos on asp.net/mvc and I saw how DropCreateDatabaseIfModelChanges can be used to auto-create or re-create the necessary database and schema. I was hoping there was some way to include the aspnet_* tables in that....
You have to create the database by yourself using the command promt.
Start that command promt and execute "aspnet_regsql". A Wizard will start
and help you create the database.
Here is nice sample =>
http://www.ezineasp.net/post/How-to-Create-Aspnetdb.aspx
If you want to give the project away. Think about
create the database as i told
create a sql script from that
build the database using SqlClient in your application on first startup
You could check if the database exists in the global.asax "Application_Start" Method
protected void Application_Start(Object sender, EventArgs e)
{
//... check if your database already exists, if not DO IT ;)
}
In the scenario that you want - your database IS a valid sql express MDF file.
This is usually the best way to share the solution otherwise you are going to have to worry about database config, setting up the db, which server, etc. If you still want to do that you'll want to right click on your data connection in the server explorer in visual studio and publish the database and generate scripts if you have anything custom otherwise use aspnet_regsql.
However I still strongly suggest if you are sharing this application you keep it in the app_Data folder and let other users choose if they want it to run elsewhere. They can publish it as they see fit using the same method.

Categories