Monday 13 October 2008

LINQ in Visual Studio 2008

To use LINQ in a project add a 'LINQ to SQL Classes' template.

this opens a .dbml file that you can drag tables onto to make classes and stored procedures to make methods.
When you drag tables across there relationships are detected.

To use linq you need to create a Data Context to connect to your classes and methods.
This is usually called 'Whatever you named your LINQ to SQL Classes' + DataContext, eg.

PDPDataContext db = new PDPDataContext();

Get Data

To get all users you might do somehting like this:

var users: = from o in db.Users
select o;

This would select every record and field from the users table.

You can then bind this like you would a dataset or datatable.

datasource = users;

To insert a record using linq we can do the following:

Create an instance of the user class created by the LINQ to SQL Classes.

User u = new User();

Set the properties:

u.Name = "Jim";

Add User:

db.Users.InsertOnSubmit(u);

Save to Database:

db.SubmitChanges();


Update a record

Get a single record:

User u = (from o in db.User
where o.userid = 2456
select o).Single();

You set the properties as before and save to the database, there is no need to InsertOnSubmit.

db.SubmitChanges();

Examples
You can group and order and use aggregate functions using LINQ, for examples go here

No comments:

Free Hit Counter