Tuesday, March 4, 2008

LINQ to SQL

This is an abstract of LINQ to SQL; this provides a better way to linq your entites class to the database tables. For example lets say you have

a table called “tbl_customer” with fields “customer_name” and “customer_id”, you would map your entity class “Customer” as follows

[Table(Name=”tbl_customer”)]

public class Customer

{

[Column(Name=”customer_id”)] public int CustomerId;

[Column(Name=”customer_name”)] public string CustomerName

}

You can query you database by making use of the DataContext class, like this…

DataContext db = new DataContext(databaseConnectinString);

Table<Customer> customers = db.GetTable<Customer>();

var query = from cust in customers

where cust.CustomerId = 12

select cust;

Simple right?

This is a simple snippet of what you can do, but LINQ to SQl provides more flexibility, like sql type conversions, complied queries etc.

Some of you would not like the mapping that done in code…I don’t either, you can use xml mapping files to do this mapping. I will post something on this soon.

No comments:

Post a Comment