Creating LINQ to SQL Entities in C#


Server Intellect


Creating LINQ to SQL Entities in C#

This tutorial was created with Visual Studio .NET 2008, but can be recreated in 2005, after downloading and installing Microsoft's LINQ Community Technology Preview release, which can be downloaded from here.

Try Server Intellect for Windows Server Hosting. Quality and Quantity!

Visual Studio.NET 2008 makes it very easy for us to create LINQ to SQL Entities using the Object Relational Designer. What it does is creates classes and methods that relate to the database columns and tables. This makes it possible for us to communicate with the data using LINQ (Language Integrated Query).

This tutorial will show how we can bypass the Designer and write the class ourselves, so that we get a better understanding of what's going on. For this example, we will be using a SQL database with one table and three columns - id, name, and city.
Once we have our database set up, we will create a new class to represent the database table structure. It should look something like this:

using System;
using System.Data.Linq.Mapping;

[Table(Name="tblPeople")]
public class people
{
[Column(IsPrimaryKey=true, IsDbGenerated=true)]
public int Id { get; set; }

[Column(CanBeNull=true)]
public string name { get; set; }

[Column(CanBeNull=true)]
public string city { get; set; }

public people()
{

}
}

It is advised to always include the table name in the class, although it is not really required if the class is named the same as the table in the SQL database. You should always declare the Primary Key, especially if you are planning on making changes to the database. IsDbGenerated is also used where the database will auto-generate the values upon insert.
In the class, we need to define a [Column] for each in the database table, and then the name of the column should be represented by the public string (or int, etc.)

Next, we are going to display the data with a GridView, and we will also add a textbox and button to the page to allow searching of the database.
Our ASPX page will look something like this:

<form id="form1" runat="server">
Name: <asp:TextBox ID="txtName" runat="server" /><br />
<asp:Button ID="butSearch" runat="server" Text="Search"
onclick="butSearch_Click" /><br />
<br />
<asp:GridView ID="GridView1" runat="server" />
</form>

Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

We are also going to need a connection string. We have the following in our Web.config file:

<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

Now we have our database set up, and our class representing the database, we can add to the code-behind to interact with our database. We will use the textbox to allow the user to search for matches in the name column of the database, and the code will go under the button click event:

string con = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataContext db = new DataContext(con);
var tPerson = db.GetTable<people>();

GridView1.DataSource = tPerson.Where( p => p.name.Contains(txtName.Text) );
GridView1.DataBind();

The above code is using a Lambda Expression, which can be a lot shorter than using a regular LINQ Query. We are simply selecting the records that match our request, and then binding the gridview with the data returned from this query. Note that GetTable<> references the class name; not the table name (if different).
When we run this web application, we are greeted with just the textbox and the button. If we leave the textbox blank and hit the button, we should be shown all the records in the database. If we enter some text, we will be shown matches from the database.

If you're looking for a really good web host, try Server Intellect - we found the setup procedure and control panel, very easy to adapt to and their IT team is awesome!

The entire code-behind looks something like this:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.Linq;
using System.Web.Configuration;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

protected void butSearch_Click(object sender, EventArgs e)
{
string con = WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataContext db = new DataContext(con);
var tPerson = db.GetTable<people>();

GridView1.DataSource = tPerson.Where( p => p.name.Contains(txtName.Text) );
GridView1.DataBind();
}
}

We used over 10 web hosting companies before we found Server Intellect. Their dedicated servers and add-ons were setup swiftly, in less than 24 hours. We were able to confirm our order over the phone. They respond to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

Download Project Source - Enter your Email to be emailed a link to download the Full Source Project used in this Tutorial!



100% SPAM FREE! We will never sell or rent your email address!
 


Comments
janlie macdovish said:

ur sample is working but u forgot to mention that

we need to add an ASSEMBLIES in the webconfig in order to have a

using System.Data.Linq

like this:

<assemblies>

<add assembly="System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>

</assemblies>

anyway thanx for this sample.

Posted 10/29/2008 at 7:04 PM
Dinesh Patil said:

The GetTable method gives us all the records in the table. If I have 2 tables, Orders and Customers, and and in Orders table i have CustId which refers to CustomerId in customer table. And when I say GetTable<Orders> it sholuld also fetch the Customer entity for me. Means I should be able to access the customer name like this: ordrer.Customer.CustName. Is there any way to do this?

Thanks in advance.

Posted 08/13/2009 at 6:32 AM
Dinesh Patil said:

I can write the code like this. But I want to make it generalized, means it should include all the referenced entities in the result. Is there any parameter in GetTable method or any setting in dbml file?

var query = (from orders in dc.GetTable<Order>()

from orderDetails in dc.GetTable<Order_Detail>()

from prods in dc.GetTable<Product>()

where ((orderDetails.OrderID == orders.OrderID)

&& (prods.ProductID == orderDetails.ProductID)

&& (orders.EmployeeID == 1))

orderby orders.ShipCountry

select new CustomerOrderResult

{

CustomerID = orders.CustomerID,

CustomerContactName = orders.Customer.ContactName,

CustomerCountry = orders.Customer.Country,

OrderDate = orders.OrderDate,

EmployeeID = orders.Employee.EmployeeID,

EmployeeFirstName = orders.Employee.FirstName,

EmployeeLastName = orders.Employee.LastName,

ProductName = prods.ProductName

}).ToList<CustomerOrderResult>();

Posted 08/13/2009 at 6:39 AM
Raibeart said:

var OrderList = from ol in db.tblOrders.Include("tblCustomer")

select ol;

This will include the customer information for display. You have to use teh include format if you want to display information. If you only want to limit it to a customer, but not display customer info, you do not have to do the include.

Posted 10/19/2009 at 10:29 AM
Robert said:

My code won't compile. This is the error I get:

The type arguments for method 'System.Linq.Enumerable.Contains<TSource>(System.Collections.Generic.IEnumerable<TSource>, TSource)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Posted 12/10/2009 at 11:04 AM
jeux des casinos said:

A nice repository based way of using linq to sql. It includes all the required functionality of paging and sorting, when binding with object data soruce.

I have uploaded the sample for you.The link is at the very top. You have to fix the connection to the correct location for the NorthWind database.

Has a sample project as well.

Posted 01/23/2010 at 2:12 AM
Essay said:

Here information regarding how to create LINQ to SQL Entities in C# is provided. He points out that Visual Studio.NET 2008 is a very efficient tool which can be used effectively to create LINQ to SQL Entities using the Object Relational Designer. He is trying to show us how we can bypass the designer and write the class ourselves so that we will have a clear idea of what is going on. After that he has given the computer program to do that. I think the specialty of this blog is that it gives attention to detail. Everything is presented in such a way that even a beginner in LINQ can easily understand it.

Posted 05/04/2010 at 9:04 PM
Jeux de garçon said:

The GetTable method gives us all the records in the table. If I have 2 tables, Orders and Customers, and and in Orders table i have CustId which refers to CustomerId in customer table. And when I say GetTable<Orders> it sholuld also fetch the Customer entity for me. Means I should be able to access the customer name like this: ordrer.Customer.CustName. Is there any way to do this?

Posted 05/27/2010 at 3:47 PM
Web Hosting said:

I've got the same problem as Robert.. that error won't leave me alone!

Posted 06/08/2010 at 3:38 AM
Flyer Design said:

The only difference here is that we now have added an extra line to select only the data items that match the text we input into the text box.

Posted 07/31/2010 at 2:25 PM
Business Gifts said:

This web application will run right now - both buttons will be active and will return data from the XML file. We can improve the implementation by adding a bit of AJAX to stop the whole page posting back. We add a ScriptManager and an UpdatePanel to the ASP page to accomplish this:

Posted 07/31/2010 at 2:26 PM
SEO Consultant said:

Thank you for taking this opportunity to discuss this, I feel strongly about it and I take pleasure in learning about this kind of topic. I already bookmarked you and I will come back to read your other useful posts.

Posted 07/31/2010 at 2:26 PM
MBT Shoes said:

cocokathy90

Posted 08/26/2010 at 8:11 AM
coach outlet said:

We will start by designing our form with Four buttons and a label. The first button will be to display all the numbers in our array, which we will hard-code for this example.

Posted 08/26/2010 at 8:12 AM
gucci bags said:

cocokathy90

Posted 08/26/2010 at 8:12 AM
Supra Shoes said:

cocokathy90

Posted 08/26/2010 at 8:13 AM
louis vuitton sale said:

cocokathy90

Posted 08/26/2010 at 8:14 AM
louis vuitton bags & lv handbags & louis vuitton & lv said:

<p>We've updated the traditional style of our <b><a href="http://www.uggboots5815.com/">UGG Classic Tall</a></b> with wooden <strong>UGG? logo buttons</strong> and elastic band closures. The <b><a href="http://www.uggboots5815.com/ugg-bailey-button-triplet-c-95.html">women's Bailey Button Triplet</a></b> can either be worn up or cuffed down adding a little variety depending on your style. All new UGG boots in our <b><a href="http://www.uggboots5815.com/ugg-bailey-button-triplet-c-95.html">Classic Bailey</a></b> Collection feature a soft foam insole covered with genuine sheepskin and have a molded EVA light and flexible outsole designed for amazing comfort with every step. <strong>Always free shipping,and almost need 5-7 days deliver to your door</strong>.</p>

<a href="http://www.uggboots5815.com/ugg-bailey-button-triplet-c-95.html"><h1>UGG Bailey Button Triplet</h1></a>

Posted 08/26/2010 at 8:14 AM
chanel handbags said:

cocokathy90

Posted 08/26/2010 at 8:14 AM
coach outlet store online said:

cocokathy90

Posted 08/26/2010 at 8:15 AM
UGG Bailey Button & UGG Bailey Button Boots said:

handlers by clicking on the Events button in the Properties window, and then double-clicking on both of the MouseHover and MouseLeave events.

Let's start with the statusstrip label.Thanks

Posted 08/26/2010 at 8:17 AM
UGG Bailey Button Triplet said:

handlers by clicking on the Events button in the Properties window, and then double-clicking on both of the MouseHover and MouseLeave events.

Posted 08/26/2010 at 8:20 AM
ugg classic boots & womens ugg boots said:

the MouseHover and MouseLeave events.

Posted 08/26/2010 at 8:23 AM
ugg classic boots & ugg boots said:

the MouseHover and MouseLeave events.

Posted 08/26/2010 at 8:24 AM
ugg classic boots & ugg boots said:

Let's start with the statusstrip label.Thanks

Posted 08/26/2010 at 8:25 AM
ugg classic boots & ugg boots & ugg classic tall & ugg classic tall boots said:

with the statusstrip label.Thanks

Posted 08/26/2010 at 8:27 AM
ugg classic boots & ugg boots & ugg classic tall & ugg classic tall boots said:

textBox3.Enabled = true;

button4.Text = "Disable >>";

Posted 08/26/2010 at 8:13 AM

Posted 08/26/2010 at 8:28 AM
xiaopohai said:
Posted 08/26/2010 at 9:13 PM
Freelance web developer said:

Thanks for this exciting help. The code is so much helpful.

Posted 09/02/2010 at 4:18 AM

Leave a Comment