Entities in LINQ to SQL

            1. What do we need to work with LINQ to SQL?

            2. What does happen when the foreach loop enumerates?


            To work with LINQ to SQL we need that each table in a database has corresponding class decorated with attributes:




    [Database(Name = "AdventureWorks")]

    public class AdventureDBContext : DataContext


        public AdventureDBContext(string connString) : base(connString) { }       





    public class Contact


        [Column(Name="ContactID", IsPrimaryKey=true)]

        public int ContactId


            set; get;



        [Column(Name = "FirstName")]

        public string FirstName


            set; get;





    class Program


        private const string _conString = @"Data Source=MS-D00115-80SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True";

        static void Main(string[] args)


            using (AdventureDBContext dt = new AdventureDBContext(_conString))


                var contacts = dt.GetTable<Contact>();

                dt.Log = Console.Out;


                IQueryable<Contact> top10Contacts = (from c in contacts

                                                        where c.FirstName == "John"

                                                                                           select c).Take(10);


                DbCommand command = dt.GetCommand(top10Contacts);











SELECT TOP (10) [t0].[ContactID] AS [ContactId], [t0].[FirstName]

FROM [Person].[Contact] AS [t0]

WHERE [t0].[FirstName] = @p0


The query variable is initialized with query expression that forms an expression tree. When the foreach loop enumerates the expression tree is used to generate the sql query using metadata from the corresponding class decorated with attributes.

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 )

Connecting to %s