Connect to SQL server using Linq, asp.net - asp.net

I`m creating a website using asp.net, and I need to use a local SQL server (using Microsoft SQL server). And I have created database and tables in it using the MS SQL Server Management Studio.
Now I successfully connect to the database and do some simple add/query using the following commands:
string connectionString = "data source=ABCD\\SQLEXPRESS;initial catalog=PMD;Trusted_Connection=yes;";
string sqlQuery = "INSERT INTO PMD (username, userID, userAddress)";
sqlQuery += " VALUES (#user, id, add)";
SqlConnection dataConnection = new SqlConnection(connectionString);
SqlCommand dataCommand = new SqlCommand(sqlQuery, dataConnection);
dataCommand.Parameters.AddWithValue("user", USER.Value);
dataCommand.Parameters.AddWithValue("id", ID.Value);
dataCommand.Parameters.AddWithValue("add", ADDRESS.Text);
dataConnection.Open();
dataCommand.ExecuteNonQuery();
dataConnection.Close();
The command above can add one column to the table, with values stated.
The query is done in a similar way. Compared with Linq, this is not very concise.
So I was wondering how can I change the code so I can use Linq.
The biggest question for me now is how to connect to the base. I already know all the syntax of Linq.
eg: var query=from c in db.username where c.Contain(“Micheal”) select c (or maybe db.PMD.username)
How can I get the db to link with ABCD/SQLEXPRESS, table PMD?

First you need an Object/Relational Mapper (O/RM). You can't just put LINQ on top of your old ADO.NET code.
Microsoft provides two: Linq2SQL and Entity Framework.
Linq2SQL has been discontinued. If I had to choose between the two, I'd go with Entity Framework.
Here you can find an introduction: http://www.asp.net/entity-framework

For example, install Entity Framework, then connect to sql server with entity framework

Related

What is the difference between .net data providers and odbc drivers?

Can you please help me understand the difference between these two technologies of connecting to databases?
I am new to the field of database connectivity, but may you can explain on specific examples which technology is used in each case? What for example should I use if I am developing the application ob Visual Studio and going to connect in with MySQL and why?
May be the question will seem stupid for the professionals, but I would be very thankful if you will clarify it for me.
A .NET data provider is a software component that provides access to a data source. They specifically designed to work in .NET applications (C#, VB.NET, etc.) and will have at least some standard classes/functions: Connection, Command, DataReader, DataAdapter (similar to the native System.Data.SQLClient classes).
An ODBC driver is very similar, but is written using the ODBC standard, and while it can be used programmatically in applications, it is also capable of being used as a data connector in any number of popular BI/reporting/ETL tools (like Tableau, QlikView, PowerBI, etc.). To use an ODBC driver in a .NET application, you'll need to use the Microsoft.Data.ODBC library.
For your use case, you'll want to use an ADO.NET data provider so that you can be sure that you're using a product that was specifically designed to be used in .NET applications. Some basic code would look similar to the following:
string connString = "server=XXX.XXX.XXX.XXX;database=myDatabase;user=myUser;password=myPassword;...";
using (MySQLConnection conn = new MySQLConnection(connString){
MySQLCommand cmd = new MySQLCommand("SELECT * FROM some_table", conn);
MySQLDataReader rdr = cmd.ExecuteReader();
while(rdr.Read()) {
Console.WriteLine("=================");
for (int i=0; i<rdr.FieldCount; i++) {
Console.WriteLine(rdr.GetName(i) + ":\t\t" + rdr.GetValue(i));
}
}
}

How to access SQL Server from my WCF web service?

VS Express 2012, SQL Server Express 2012, Win 8.1
Hello,
I have a (very) simple WCF hosted as a web service on IIS. I also have a SQL Server instance (with 1 table) installed on the same machine.
I need a step-by-step guide on how to connect to SQL from the WCF (VB) and retrieve a single record from the table (ie: "SELECT LAST NAME FROM MYTABLE WHERE PK = 1;"). That's it. I don't need a 1,200 page manual -- which is all Google keeps throwing at me.
Anyone know of a quick, clean resource?
Thanks,
Jason
The main classes that are involved are SqlConnection and SqlCommand. The documentation of the classes contains some samples on how to use them. To get you started, here is a small sample:
Dim connStr = "Data Source=SQLServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=SSPI"
Using conn As New SqlConnection(connStr)
conn.Open()
Using cmd = conn.CreateCommand()
cmd.CommandText = "SELECT LAST_NAME FROM MYTABLE WHERE PK = #pk"
cmd.Parameters.AddWithValue("#pk", 1)
Dim result = cmd.ExecuteScalar()
If Typeof result Is DbNull Then
' Handle null value
Else
' Otherwise
End If
End Using
End Using
This sample assumes that you want to retrieve a single cell as in your statement. If you want to retrieve tabular data, have a look a the SqlDataReader or SqlDataAdapter class.
Please note that - especially in server applications - it is important to dispose of the created instances properly.
There is no difference on using ADO.NET in a WCF service or in a normal application from the point of view of the classes required.
The first thing needed is a connection string that allows your SqlConnection object to find the host and the database that you want to use. Here examples on connection strings
Then you usually need a SqlCommand that encapsulates the SQL text and parameters needed to retrieve the data (Here you setup your SELECT statement and conditions)
Finally you need a SqlDataReader that get the result of the command execution and allows you to loop over the results.
Here a sample that could get you started.
Keep in mind that this is just a minimal todo-list and there are numerous other ways to work with data. Basic objects like SqlDataAdapter, Dataset, DataTable present different ways to load data from a database and use that data. Then on top of these there are technologies like Linq To Sql and Object Relational Mapper tools that abstract the data access and offer high level functionality on top of data.
That's probably the reason you get so much informations on data access technologies

FoxPro Database and asp.net

I have a website that uses asp.net 3.5 and Sql server 2008 as backend data store . now we want to add a new page to our website . but the data that we want to share in this page is already being created and saved by a FoxPro software in one of our local systems.
I've no experience in FoxPro . is there any way to use this data in our site ? specially without being have to create a new database in server and importing or writing all records all over again ? what is the best way in such a situation ?
by the way , is it possible to change the extension of a FoxPro database or not ? something like Database.customExt ?
You can connect to a FoxPro database using an OLEDB datasource in ADO.NET. It's up to you whether you feel the need to import the data into SQL Server or just access it directly in FoxPro. It would depend on whether you want to join the data with the SQL Server data in queries for one thing.
In addition to the answers that you already got. You might be interested in using LINQ to VFP or VFP Entity Framwork Provider to make the data access even easier by using LINQ.
You could create a linked server to this Foxpro Database.
Also, Foxpro tables can have any extension. However, you'll have to specify the extension when using the table or database. For Example:
OPEN DATABASE MyFoxProDatabase.customExt
USE mytable.custonExt
You have several options for structuring your data access to FoxPro. You can put the ADO.NET data access code in the codebehind, in it's own c# library or use the objectdatasource for 2 way binding.
private void LoadData(string parameter)
{
string sql = "SELECT a.myfield FROM mytable.customExt a WHERE a.whereField=?";
using(OleDbConnection conn = new OleDbConnection(myConnectionString))
{
using (OleDbCommand command = new OleDbCommand(sql, conn))
{
command.Parameters.AddWithValue("#Parameter", parameter);
try
{
conn.Open();
using(OleDbDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection))
{
myGridView.DataSource = dr;
myGridView.DataBind();
}
}
catch (Exception ex)
{
throw;
}
}
}
}
Here is a sample connection string to use in web.config:
<add name="myData" connectionString="Provider=VFPOLEDB.1;Data Source=C:\MyFiles\" providerName="System.Data.OleDb"/>
I belive ou can use a custom extension to your FoxPro tables and databases. All your SQL statements would then need to explicitly use that extension.
SELECT t.MyField FROM MyTable.customExt t
While you can change the extension for a Visual FoxPro table, that only affects the DBF file. If the table has any memo fields, there's an associated FPT file, for which you can't change the extension. Similarly, if the table has an associated index file, it must have a CDX extension.
So, if the reason you want to change the extension is to allow multiple tables with the same filestem, don't. It's a good way to really mess things up.

Convert Access data base to SQL Server

I've created an application using ASP.NET with Access DB, now I found somee.com who support only SQL Server DBs, so Now I must convert my Access DB to SQL Server DB.
Is there any tool who can do the trick ?
This is some code I'm using in my web application :
Public Shared Function conecter() As OleDbConnection
Dim MyConnexion As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data source=" & System.AppDomain.CurrentDomain.BaseDirectory & "/Learning.mdb")
MyConnexion.Open()
Return MyConnexion
End Function
Public Shared Function lecture(ByVal requete As String) As OleDbDataReader
Dim Mycommand As OleDbCommand = conecter().CreateCommand()
Mycommand.CommandText = requete
Dim myReader As OleDbDataReader = Mycommand.ExecuteReader()
Return myReader
End Function
In this case, If I convert my database I must change the OleDbConnexion and other things or I can just leave them like that ?
Your connection string will need to change. Connectionstrings.com is a good resource for this if you're having problems figuring out how to set up a SQL connection string.
For upward migration, take a look at the Access Upsize Wizard - this link is for 2002 since I'm not sure what access version you have.
If for some reason you do not have sufficient access to your SQL database to handle an upsize directly, you'll likely need to just generate the database schema and knock out a bit of migration code.
If you have access 2007, there is inbuilt option convert access database to SQL other wise there are somany tools available for free.
bullzip free converter
Try MUST
It was developed by a colleague of mine (we designed the website: www.upsizing.co.uk).
It does a fair bit more than the MS tools.

ASP.NET MVC 2 - user defined database connection

I am looking to port my very basic DBMS software from classic ASP to ASP.net - however the user would need to input the connection details in order to connect to their specific DBMS server.
Is this at all possible with ASP.NET MVC (very similar to DSN-less connections in ASP).
Cheers,
Joel
The question should really be "is this possible with .NET", ASP.NET MVC is not a database technology, and DSN-less connections aren't ASP technology either. In .NET, it is the ADO.NET framework that allows you to access database resources, and it can be used from any .NET code, be it desktop, web and mobile too.
There are some specialised libraries for certain platforms, .NET includes native support for Sql Server, you can get the MySql Connector for .NET, etc.
All of these providers are built around the ADO.NET provider model, you can either use them explicitly, or you can use the provider-agnostic method. Here are two examples, the first being Sql Server:
string connectionString = "Server=....";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand("SELECT [Name] FROM [People]"))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
// Do something here.
}
}
}
In the above example, I'm using the specific Sql Server ADO.NET types to create a connection to a database and execute an arbitrary query against it.
If you are intended to support multiple database platforms, it's probably best to design your code such that it can utilise the ADO.NET Factory classes which are specialised factories geared to the creation of platform specific types. In the example below, I've used the Factory classes to access a MySql Server database:
string connectionString = "Server=....";
DbProviderFactory factory = DbProviderFactories.GetFactory("MySql.Data");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.CommandText = "SELECT `Name` FROM Page";
connection.Open();
using (DbDataReader reader = command.ExecuteReader())
{
// Do something here.
}
}
}
Not the perfect example, but enough to get you going, but it's important to remember that DSN-less connections are not tied to ASP or ASP.NET.
Hope that helps.

Resources