Linq to SQL (1)

You can crate a Plain Old CLR Object to map the underlining database table w/o the help of the LINQ-to-SQL designer. To represent a customer class, you need the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Text;
 
namespace LinqToSql
{
    [Table(Name="Customers")]
    public class Customer
    {
        [Column]
        public string customerId {get; set;}
        [Column]
        public string companyName {get; set;}
        [Column]
        public string city {get; set;}
        [Column]
        public string country {get; set;}
    }
 
    class LinqToSql
    {
        static void Main(string[] args)
        {
            string connString = @"Server=.SQLEXPRESS; 
            Database=Northwind; Trusted_Connection=Yes";
            DataContext db = new DataContext(connString);
 
            // crate typed table
            Table<Customer> customers = db.GetTable<Customer>();            
            //query database
            var custs = from c in customers
                        where c.country =="USA"
                        select c;
            //display customers
            foreach (var cust in custs)
            {
                Console.WriteLine(
                    "{0} {1} {2} {3}", 
                    cust.customerId, cust.companyName, cust.city, cust.country
                    );
            }
            db = null;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *