Home > Development > Look of LINQ

Look of LINQ


I finally decided to take a look at LINQ. A quick google around took me some time to figure out how to get a full example working (which references are needed etcetera…) Therefor I decided to write a quick tutorial on how to work with DLINQ. To make this sample working you should create a SQL Server database Blog with 1 table in it called Post. In that table you will have id, title and body as columns, where id is a unique identifier (int auto-increment)
Create a new asp.net website project and add a class library called Business to it as well.Rename Class1.cs to Post.cs (also make sure the class is renamed to Post)
Ok, now we are good to go. First of all we will add the connectionstring to our web.config:

<connectionStrings>
<add name=BlogConn
connectionString=Data Source=(local);Initial Catalog=Blog;Integrated Security=True

providerName=System.Data.SqlClient />
</connectionStrings>

Your app.config should look like the above. Now, what we will do first is create a class named Post and add all the private variables to it and the properties.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Linq;
using System.Data.Linq.Mapping;
namespace Business
{
[Table(Name = “Post”)]
public class Post
{
private int _id;
private string _title;
private string _body;
[Column(Storage=“_id” , IsPrimaryKey=true)]
public int Id
{
get { return _id; }
set { _id = value; }
}
[Column(Storage=“_title”)]
public string Titel
{
get { return _title; }
set { _title = value; }
}
[Column(Storage=“_body”)]
public string Body
{
get { return _body; }
set { _body = value; }
}
}
}

 

If you put it like this, it will not compile. Add a reference to the System.Data.Linq dll and then your business should compile. What does all of the tags above the properties mean: [Table(Name = “Post”)] : it tells LINQ how the table is called in the database
[Column(Storage=”_id” , IsPrimaryKey=true)] : this property is stored in the private variable _id. Should our table column name be different from id, we would have to use [Column(Storage=”_id” , Name”DBColumnName”, IsPrimaryKey=true)]
Ok, so now we have connected Linq to the database fields. How do we tell Linq which database to do and what queries to perform?
We will create a new class in the Business Project called “BlogDB”. That class will look like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.Linq;

namespace Business
{
class BlogDB : DataContext
{
public Table<Post> Post;
public BlogDB(string connection) : base(connection) { }
}
}

This class just exists to make our life a bit easier. BlogDB inherits from DataContext. The DataContext class allows you to use any data holder (xml, array,…) as datasource for your LINQ code. Now up to the LINQ work. I made a Posts class that is a Collection of Post classitems:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Configuration;

namespace Business
{
public class Posts : CollectionBase
{
public void GetAllPosts()
{
BlogDB db = new BlogDB(ConfigurationManager.ConnectionStrings[“BlogConn”].ConnectionString);
var q =
from p in db.Post
where p.Titel == “Test”
select p;
foreach (var pst in q)
base.InnerList.Add(pst);
}
}
}

For those who aren’t familiar with ConfigurationManager, it’s the next gen version of ConfigurationSettings.AppSettings. To make it work a simple using System.Configuration will not do the trick. You will need to manually add the System.Configuration.dll to your references. Ok, so now we have a collection that contains all the posts that have test as title. Add a few items to your database of which at least 1 has test or Test as title. What we are doing here is getting all teh posts with the LINQ query:

var q = from p in db.Post
where p.Titel == “Test”
select p;

 

and then putting all the results in the collection. One more step to go is showing it on screen. Add a dropdownlist to your web form in your web project and then put the following codebehind:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using Business;
namespace Blog
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Posts p = new Posts();
p.GetAllPosts();
DropDownList1.DataSource = p;
DropDownList1.DataTextField = “Titel”;
DropDownList1.DataBind();
}
}
}

 

Load it up and everything should work just fine. Don’t hesitate to ask me questions through the comments.

Advertisements
Categories: Development Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: