How do I connect to an existing database in ASP.NET MVC? - c#

I'm just starting to learn C# and ASP.NETMVC, but every example I've found puts the database in the App_Data folder. I don't want to do this.
I'd like to create a new version of Nerd Dinner and move the connection string to the web.config, but I can't find any examples on how to do it. My database is called NerdDinner and I'm using SQL Server Express.
What's the correct syntax to add the new connection string to my web config? Does this have any effect on creating LINQ to SQL classes?

I always go to http://www.connectionstrings.com/ when I forget how a connectionstring is written.
Standard security SQL Server 2008
Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;
Here is an article on MSDN talking about How to: Read Connection Strings from the Web.config.
You have a section almost at the top in your Web.config called connectionstrings, it could look something like this:
<connectionStrings>
<add
name="NorthwindConnectionString"
connectionString="Data Source=serverName;Initial
Catalog=Northwind;Persist Security Info=True;User
ID=userName;Password=password"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
I would recommend however that you also look in to Entity Framework which is an abstraction between your code and the database, it makes it easier to work with "objects" in your database. You can find an introduction to ADO.NET Entity Framework here. But first of all you should focus on getting your connection up and running to your database using the information at the top.

An additional way to have your context 'point' to the connextionsStrings line in the web.config file is to try this constructor.
public class MainDB : DbContext
{
public MainDB() : base ("name=DefaultConnection")
{
}
public DbSet<User> Users { get; set;}
}
Then change the name to DefaultConnection in the web.config file.

Related

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>

Single DbContext using multiple connection strings per environment

I know that currently a group of developers that I joined do not use Entity Framework, but they are fine with me using it.
Currently their connection strings are stored in web.config (or app.config)
<add name="LH_RPMDB"
connectionString="data source=localhostdb;Database=dbsim;user id=sim;password=sim;Application Name=SIM-LH;"
providerName="System.Data.SqlClient" />
<add name="DEV_RPMDB"
connectionString="data source=devdb;Database=dbsim;user id=sim;password=sim;Application Name=SIM-dev;"
providerName="System.Data.SqlClient" />
<add name="QA_RPMDB"
connectionString="data source=qadb;Database=dbsim;user id=sim;password=sim;Application Name=SIM-qa;"
providerName="System.Data.SqlClient" />
Now they are telling me to use LH for localhost, then upper environments will they fall in line with DEV and QA.
I'm NOT sure if they are "detecting" the URL for what server as I'm new to the team. I am just trying to get my DbContext in place to consume the proper database connection string.
Currently I just have 1 DbContext with one connection string and thus
public class RPMContext : DbContext
But I see that "they" are using code like this:
ws.Url = ConfigurationSettings.AppSettings(ConfigurationSettings.AppSettings("Environment") + "_SNTRAX")
However, I am wanting to leverage the several connection strings for all the environments with a single DbContext.
I found some code that shows this example web.config
<connectionStrings>
<add name="DefaultConnection"
connectionString ...
then
public TrackerContext() : base("Name=DefaultConnection") {}
another example I was seeing is
public partial class HOLDbEntities
{
public HOLDbEntities(string connectionString)
: base(connectionString)
Here is a stackoverflow article I had seen, it doesn't really get me to where I want to be though
Entity Framework - using the same DbContext with different connection strings
What do I want? Well I know that I need to have all the environments connection strings in the app.config (not using web.config with this project as it is a console application).
What I do not know is how to know what environment that I am in for the application to be somewhat dummy proof and just "automatically "work"
I'm thinking that reading the URL, but actually it is a console application So I wonder if per server environment if there should be an appsetting changed for which connection string to use so "LH" vs. "DEV" and "QA" and then a few others...
Thoughts?
Try the Configuration Extension perhaps?

Changing ConnectionString authorization method cause migration fail

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.

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.

Adding ADO.Net Entity Data Model using machine.config connection string

I am at the beginner level of learning MVC5 using EF6. Basically I am trying to use a connection string defined in machine.config rather than using web.config whilst creating the ADO.NET Entity Data Model. The reason why I am using machine.config for connection string is; we have different SQL Cluster servers and application servers. On local machine we use local SQL Server instance but on beta/Live SQL server we use different instance names. The credentials are different too. so on each application/web server we have defined the ConnectionString in machine.config for the same database name but with different credentials.
Is there a way I can use ConnectionString specified in machine.config whilst using the wizard to create ADO.Net Entity Data Model or can I give reference of machine.config ConnectionString to my app web.config or is there any other way to solve this problem?
I am using Database First technique using MVC5. I have tried the following after creating edmx by using local DB and then tried to change the connection string in my context class:
public partial class MasterDataEntities : DbContext
{
public MasterDataEntities()
: base(string.Format("{0}", getConnectionString()))
{
}
public static string getConnectionString()
{
Configuration config = ConfigurationManager.OpenMachineConfiguration();
return config.ConnectionStrings.ConnectionStrings["masterdata"].ConnectionString;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
}
Error: OnModelCreating
Additional information: 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.
Kind Regards
You can simply define your connection string in machine.config. When you use the configuration manager it will look in the machine.config first for your appsettings and then your application config file.
Check this article on Configuration files
string innerConnectionString = ConfigurationManager.ConnectionStrings["Inner"].ConnectionString;
<add name="Inner" connectionString="Data Source=SomeServer;Initial Catalog=SomeCatalog;Persist Security Info=True;User ID=Entity;Password=SomePassword;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
After several experiments on the MVC and EF Database First approach, I found that the problem was in the machine.config's connection string. Entity Framework doesn't like the standard connection string. Connection String must have the metadata Info about the DBContext resources and the provider name for EF. My standard ConnectionString in the machine.config was:
<add name="masterDataConnectoinString" connectionString="Data Source=Instance1;Initial Catalog=masterData;Integrated Security=True;"/>
Then I copied the ConnectionString from web.config to maching.config which was created by default when I added the Entity Data Model (edmx):
<add name="masterDataConnectionString" connectionString="metadata=res://*/Models.DBContext.csdl|res://*/Models.DBContext.ssdl|res://*/Models.DBContext.msl;provider=System.Data.SqlClient;provider connection string="data source=Instance1;initial catalog=masterData;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
And then specifying the connectionstring name to be used as I have shown in my question for MasterDataEntities, solves the problem.
Using machine.config's ConnectionString creates another issue. If you amend the database, e.g add another column into any table and would like to update the Entity Data Model (edmx) with the new change, you right click the edmx Diagram and then click Update Model from Database, which will not work. The wizard will ask you to specify the new connection, which is not right. It should offer you to Add/Refresh/Delete tables or views or procedures.
To solve this problem temporarily I kept the connectionString into my web.config but commented out. If I had to update the model from the database, uncomment the web.config connectionString and set back your (in my case) MasterDataEntities to use web.config:
public partial class MasterDataEntities : DbContext
{
public MasterDataEntities()
: base("name=masterDataConnectionString"))
{
}
}
Which updates the model. If anyone got a better solution please please let me know. Thanks

Categories