How to add SQL Server database to my VS11 Website? - sql-server

I have a website project (C#/ASP.NET) opened in Visual Studio 11 (beta) which works with the built-in SQL Server Compact Edition. But, I would rather use my SQL Server 2012 which is installed on this machine, and I have my tables already created in it.
Question is, how do connect to it from VS11? Do I add it in the App_Data folder where I have the Compact database?
Right now I am opening my pre-made database with the
var db = Database.Open("StarterSite");
command.

If you already have the database created on SQL Server 2012, then just use it!
No need to add it to your project (and most definitely don't copy it into App_Data!).
Just create a connection string in your web.config something like:
<connectionStrings>
<add name="YourConnectionStringNameHere"
connectionString="server=(local);database=YourDatabase;Integrated Security=SSPI;" />
</connectionStrings>
and then use that in your app using all the normal ADO.NET components like SqlConnection or SqlCommand:
string connectionString = WebConfigurationManager.ConnectionStrings["YourConnectionStringNameHere"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("your-sql-statement-here", conn))
{
// do work in your database here....
}
Or use something like Entity Framework to make your life even easier!

It will depend on the technique you wish to use to connect to the SQL server database. I prefer to set my connection string in the web.config and use that when connecting to my database. There are several options you might want to explore. Here is a good MSDN article explaining some techniques.
Connecting to Databases in ASP.NET

Related

Cant connect to MSSQL Database via .net core 3.1 Application

i have a problem:
i am using .net core 3.1 WPF Application to connect to MSSQL SERVER 2016.
The Code:
SqlConnection conn = new SqlConnection("Server=MYSERVERNAME\\SQLEXPRESS;Database=MYDB;User ID=dbRead;Password=myPASSWORD;");
conn.Open();
i searched a lot and found this: https://github.com/dotnet/SqlClient/issues/367
After a while i get a timeOut exception so i added Connect Timeout=60
and now the connection can be established, but maybe after >20 seconds.
The Server has also an old version of MSSQLSERVER installed 2012.
(Because we upgraded from 2012 to 2016)
This version has the instance MSSQL and with this instance and the same connection string (MYSERVERNAME\\MSSQL) i have no issues.
If iam using a .netframework application no error occures.
So i dont know what i have to do?
Maybe somebody had the same problem.
Thanks
UPDATE:
After some research i found this:
Dot net Core – How to fix: TimeOut-Error to MSSQL 2017 (which does not happen with .Net 4.7.1)
Forcing to use named pipes by specifying np: qualifier in the server parameter in the connection string does the job
SqlConnection conn = new SqlConnection("Server=np:xxx.xxx.xxx.xxx\\SQLEXPRESS;Database=MYDB;User ID=dbRead;Password=myPASSWORD;");
conn.Open();
Data Source=[localhost];Initial Catalog=[database];Persist Security Info=True;User ID=sa;Password=[password]
remove 'sqlexpress'
make sure you are able to connect using proper creds w/ azure data studio or ssis.
---- Dotnet EF6
also if you are using EF6 (and have it setup) you can just add it to your scaffolding. makes life a bit easier if you are using the cli
dotnet ef dbcontext scaffold 'Data Source=[localhost];Initial Catalog=[database];Persist Security Info=True;User ID=sa;Password=[password]' Microsoft.EntityFrameworkCore.SqlServer -o 'Models/[database]/'
docs: https://www.learnentityframeworkcore.com/migrations/commands/cli-commands

create database before start programming by asp.net mvc 5?

I'm trying to learn MVC 5 and I have problem to connect to my database (SQL Server) I searched and find some solution but didn't work for me. So I want to know I have to create a database, a table and diagrams first, before I start to programming Asp.Net MVC 5 web application?
You can connect to your SQL Server using SQL Server Management Studio and create a database and a user for your application.
You then add the correct connection string an put it in your web.config. This depends heavily on your database setup. Here is a basic example (you need to at lease fill in Servername, UserId and Password):
<add name="ConnectionStringName"
providerName="System.Data.SqlClient"
connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=False;User Id=userid;Password=password;MultipleActiveResultSets=True" />
More options can be found in the Documentation
If you use one of the CRUD templates, the database will be created through Entity Framework for you locally. If it's not connecting to the generated database, you can try the following code in the Application_Start method:
protected void Application_Start()
{
System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseIfModelChanges<schoolcontext>());
using (var context = new SchoolContext())
{
context.Database.Initialize(force: true);
}
}

Can't connect SQL Server 2016 Developer via connection string generated by .edmx file

I'm working on a project using SQL Server 2008 Express. I had an instance called SQLEXPRESS and I used to connect to the DB via this connexion string :
<add name="MyConn" connectionString="metadata=res://*/MyDataModel.csdl|res://*/MyDataModel.ssdl|res://*/MyDataModel.msl;provider=System.Data.SqlClient;
provider connection string="data source=PCNAME\SQLEXPRESS;initial catalog=DbName;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
This connection string was generated by .edmx file (I'm working on an ASP.NET MVC project, database first, and Entity Framework) and it worked fine.
I recently installed SQL Server 2016 with a Developer Licence. During the install process, I used the default instance, which is MSSQLSERVER. For information, the generated InstanceID is MSSQL13.MSSQLSERVER.
I have a SQL project in my solution to regenerate my tables on my new SQL Server; I could connect easily to the server via the wizard.
I also used SQL Server Management Studio to verify everything was fine on the server, and it works perfectly (tables are generated, connection was OK).
However, my code is unable to connect to the server and systematically failed to the first call with error 26 - can't locate server instance
Here is what I've tried so far:
Change the data source parameter of the connexion string to localhost , ., .\MSSQLSERVER, .\PCNAME, PCNAME.MSSQLSERVER, PCNAME.MSSQL13.MSSQLSERVER, DOMAIN.MSSQLSERVER, DOMAIN\PCNAME => Doesn't work
Verify SQL Service are running => They are
Create an .udp file, connect to my server, and copy/paste the generated connection string : Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=MyDB;Data Source=PCNAME => Doesn't work
Regenerate my .edmx file (and the connection stirng) => Doesn't work
Verify this suggestion => It was already correct
Why does all the connection wizards seems to work (SSMS,
.udl file, .edmx generator, my DB project), whereas my code is unable to reach the server? I didn't change any line of code.
EDIT : The crazy thing is I have a log database on the same server, the connexion string is
<add name="NLogConn" connectionString="Data Source=localhost;initial catalog=DBLOG;integrated security=True" providerName="System.Data.SqlClient" />
And it is actually logging the network error !! So is it really a connection string error or an EF error ? I'm using the latest EF version, 6.1.3 on each project referencing EF (The main and the DAL layers)
Before going off the deep end on what it could be let's start with a working connection string I just tested on my local machine on Visual Studio 2017 Enterprise with Entity Framework 6.1.3.
<connectionStrings>
<add name="TesterEntities" connectionString="metadata=res://*/Tester.csdl|res://*/Tester.ssdl|res://*/Tester.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=Tester;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
The marked up connection string is:
="data source=.;initial catalog=Tester;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
For my test connection I am using my local server for a default instance also of 2016 developer edition(. is abbreviation for this). I am using integrated security and my database name(initial catalog) I am targeting is Tester.
There are a few things to consider if Entity Framework(EF) is not properly hitting a target.
What version of EF are you using? Before MS moved to Core, I believe the last .NET full edition of EF was 6.1.3. Ensure you are on the most current version on Nuget download.
If you go from Express to a full fledged SQL the connection string's 'provider' often will not be the same I believe. Or it could be the local default instance before sql is installed is different. Ensure you don't overwrite an existing connection string with this. The provider should be: 'provider=System.Data.SqlClient'
You are referencing a project of EF in ANOTHER project. Each project that references EF should be having the NuGet package for EF as well as a config file with the connection string. EG: I have a console project for testing things I write and reference another project called 'EF Testing' and I don't have an app config with a connection string. It won't work.

Difficulty Connecting To SQL Server Express 2012 from VB.NET (Express)

I am trying to connect to a locally installed instance of SQL Server 2012 Express using VB.NET. I have been able to successfully connect to the database using the drag-and-drop connection tool, which gives me this connection string:
Data Source=mycomputername\sqlexpress;Initial Catalog="my space containing database name";Integrated Security=True
I can successfully test this connection. Now, I want to populate a datagrid from a table in this database, so in the "root" (what do you really call this place?) of the project I have:
Imports System.Data
Imports System.Data.SqlClient
and in the form definition (before any event handlers) I have
Private cn As New SqlConnection("Data Source=mycomputername\sqlexpress;Initial Catalog=[my space containing database name];Integrated Security=True;")
Private da As New SqlDataAdapter("select * from MyTable", cn)
Private ds As New DataSet
Private cmb As New SqlCommandBuilder(da)
And this is where the train goes off the tracks. I get the error:
Cannot open database "MyDatabase" requested by the login.
The login failed. Login failed for user 'MyLogin'.
I have made sure that SQL Server Express has the Remote Login check box checked, and tried other variations on the connection string, but no luck. Ideas much appreciated.
Are you using ASP.NET? It's possible that your application runs under a different user than your visual studio (Integrated Security uses your windows authentication, based on the user your application is impersonating - in a web application, that's usually someone like NETWORK SERVICE). You'd just have to add this user as one of the users of your SQL server and database.
EDIT: I see it now. '\s' is a special character in a string.
use this as your connection string:
"Data Source=mycomputername\\sqlexpress;Initial Catalog=[my space containing database name];Integrated Security=True;"
EDIT: No, my bad, you're using VB, this kind of escaping is used in C#.

What do I change to convert my Entity Frameworks 4.1 based code to use a regular connection to SQL Server?

VS2010 C# SQL Server 2008 Express
I developed a couple of apps using Entity Frameworks 4.1. I used the database first method (I think) in that I created a database in Visual Studio 2010 and then created a model and finally the code from the model to access the database. This worked and I found that the IDE and the application uses a user instance of SQL Server 2008 Express.
I found out that User Instances are no longer in vogue and have been deprecated. So I guess I should move the database base files to the data directory of SQL Server. Easy enough.
But now will the EF infrastructure continue to work if I remove the User Instance from the connection string and point it to the main SQL Server? Do I have to regenerate the model? Is there some other course of action I should take?
You can set the connection string for your application using the app.config or web.config files.
Add the connection string as you would for any other application:
<configuration>
<connectionStrings>
<add name="sampleName"
providerName="System.Data.SqlClient"
....
Next, for your DbContext you Point it to your connection string:
public class sampleContext : DbContext
{
public sampleContext() : base("name=sampleName")
}
With these you should be able to set any configuration string you like. With this in mind, I'd also like to point you to this article on migrations for plating your database: http://msdn.microsoft.com/en-us/data/jj554735

Resources