user1739292
user1739292

Reputation: 25

Connect to SQL server using Linq, 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?

Upvotes: 1

Views: 1714

Answers (2)

Dennis Traub
Dennis Traub

Reputation: 51694

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

Upvotes: 1

Gábor Plesz
Gábor Plesz

Reputation: 1223

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

Upvotes: 0

Related Questions