C# – LINQ for SQL Server. [LINQ to SQL]

Standard

        As mentioned earlier LINQ feature supports SQL Server (Relational Database). I have created simple console program to test this feature. Just create DataContext using DB connection string. [Unfortunately my SQL server account not allows to create the user instance using MDF file path getting Sql Exception with “Generating user instances in SQL Server is disabled”. That’s why I have used this DB connection string to create the DataContext.] This is the primary object, after that accumulate the data (in memory) of specific SQL table (Student) using attribute mapping and generic table collections. Then as usual query the information using LINQ. Just known from the MSDN this feature is extension of ADO.NET technology.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Data.Linq; //add reference for this namespace (3.5 or 4)

using System.Data.Linq.Mapping; //for table attribute

using System.Text;

using System.Data;

namespace LINQtoSQL

{

class Program

{

static void Main(string[] args)

{

DataContext dc;

//dc = new DataContext(@”C:\Program Files\Microsoft SQL Server\MSSQL.3\MSSQL\Data\test.mdf”);

//Creating DataContext using mdf file path getting Sql Exception with “Generating user instances in SQL Server is disabled. Use sp_configure ‘user instances enabled’ to generate user instances.”

//My user account not allows to edit the enable user instace values in SQL Server Express 2005 that’s why

//I am creating DataContext using connection string as below.

dc = new DataContext(@”Data Source=THOSTHISINS02\SQLEXPRESS;Initial Catalog=test;Integrated Security=True;Pooling=False”);

// Using generic Table class to creat student collections

Table<student> Student = dc.GetTable<student>();

//Query the information using simple LINQ from student collection (Student)

var query = from s in Student orderby s.class_id descending

select s;

foreach (var value in query)

Console.WriteLine( “{0} \t\t {1} \t\t {2}”,value.student_id, value.student_name, value.class_id);

Console.ReadLine();

}

}

//Mapping SQL table with this class – using System.Data.Linq.Mapping;

[Table(Name=“Student”)]

internal class student

{

//Mapping SQL Table Column and its properties

[Column(Name=“Student_Id”,IsPrimaryKey=true)]

internal Int16 student_id = 0;

[Column(Name=“Student_Name”)]

internal string student_name = string.Empty;

[Column(Name=“Class_id”)]

internal Byte class_id = 0;

}

}

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