0% found this document useful (0 votes)
209 views

Linq Notes

LINQ to SQL dbml is not included by default in Visual Studio 2019. To use it, go to Tools > Get Tools and Features and add LINQ to SQL. LINQ allows querying different data sources using a uniform C#/VB syntax. It maps database tables to classes and performs type checking. Common CRUD operations like insert, update, delete can be performed using LINQ to SQL.

Uploaded by

Pankaj Haldikar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
209 views

Linq Notes

LINQ to SQL dbml is not included by default in Visual Studio 2019. To use it, go to Tools > Get Tools and Features and add LINQ to SQL. LINQ allows querying different data sources using a uniform C#/VB syntax. It maps database tables to classes and performs type checking. Common CRUD operations like insert, update, delete can be performed using LINQ to SQL.

Uploaded by

Pankaj Haldikar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

LINQ to SQL dbml is not part of default installation in visual studio 2019.

If you want to use it then do the


following –

Go to Tools  Get tools and Features option

LINQ : Language Integrated Query

LINQ is query language designed by Microsoft in .net3.5 framework designed similar to SQL.

LINQ (Language Integrated Query) is uniform query syntax in C# and VB.NET to retrieve data from different
sources and formats. It is integrated in C# or VB, thereby eliminating the mismatch between programming
languages and databases, as well as providing a single querying interface for different types of data sources.

Linq to object

Write c# program to copy all numbers greater than 40 to another array.

class Program

static void Main(string[] args)

int[] arr = { 12, 45, 6, 78, 8, 90, 1, 34, 56, 54, 57, 89 };

int count = 0;

for (int i = 0; i < arr.Length; i++)

if (arr[i] > 40)

count++;

}
}

int[] barr = new int[count];

int index = 0;

for (int i = 0; i < arr.Length; i++)

if (arr[i] > 40)

barr[index] = arr[i];

index++;

Console.WriteLine("numbers greater than 40 are");

foreach(int i in barr)

Console.Write(" " + i.ToString());

Console.WriteLine("numbers greater than 40 in ascending order");

Array.Sort(barr);

Console.WriteLine("numbers greater than 40 are");

foreach (int i in barr)

Console.Write(" " + i.ToString());

Console.ReadKey();

}
}

// Using Linq

var barr = from a in arr where a > 40 orderby a


descending select a;
Console.WriteLine("numbers greater than 40 in
descending order");
foreach (int i in barr)
{

Console.Write(" " + i.ToString());


}

Console.ReadKey();
}

LINQ to SQL

SQL LINQ

Runtime Syntax checking of sql statements Compile time syntax checking

Not Type safe Type Safe


No Intellisense support Intellisense support

Debugging of sql statement not possible Debugging of Linq statement is possible

Code is combination of object oriented and Pure object oriented code


Relational

In LINQ following conversions takesplace.

Table Class
Columns Properties
Record Instances
Stored procedure Methods

Demonstration of CRUD operations using LINQ


Steps for to work with Linq to SQL

Step1 :

To work with Linq to Sql first we need to convert all the relations objects of database into object oriented
types and this process is known as ORM (Object Relational Mapping). To perofrm ORM we are provided
with tool known as OR designer.

Steps for to work with Linq to SQL

Step1 : Perform ORM by adding OR Designer

Step2: Adding a reference for an assembly i.e. System.Data.Linq

Step3: Write connection string to config file.

Create table Employee in CompnayDB databse as shown below


create table Employee
(
Eno int primary key,
Ename varchar(50),
Job varchar(50),
Salary money,
Dname varchar(50)

)
Step1 : Perform ORM by adding OR Designer

1. In project add new item LINQ to SQL classes. It will add dbml file to project (database markup
language). Preferred name is databasename. It will add ORM tool and display two panels in it.
Left side panel for database
Right side panel for stored procedure.

It will add companyDB.designer.cs file which contains designer code writeen by visual studio which
contains CompanyDBcontext class derived from System.Data.Linq.DBContext for compnayDb
database which helps for to connect to the database whenever we create instance of class/

companyDBcontext reads connectionstring from config file and helps you to connect to database by
creating instance of this class. It also contains overloaded constructors.
2. Drag table to which you want to connect in left side pane. Which shows following window in pane.

Which performs two tasks


a) In config file ORM designer adds connectionstring.

<connectionStrings>
<add
name="WindowsFormsApplication1.Properties.Settings.CompanyDBC
onnectionString"
connectionString="Data Source=.;Initial
Catalog=CompanyDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
b) It will add 5th constructor to dbml file.

public EmployeeDBDataContext() :

base(global::WindowsFormsApplication1.Properties.Settings.Def
ault.CompanyDBConnectionString, mappingSource)
{
OnCreated();
}
c) It adds property Employees which returns table of Employee.
d) It adds class Employee containing properties for each field of table

In this way table get converted to class, attributes get changed into properties. And at time of execution of
application objects of class get instantiated.

For to load data of table we can make use of property Employees.

Place Datagridview control on form

At form load write following code.

private void Form1_Load(object sender, EventArgs e)


{
EmployeeDBDataContext dc = new
EmployeeDBDataContext();
dataGridView1.DataSource = dc.Employees;

Insert record using Linq


 private void button1_Click(object sender, EventArgs e)
{
dc = new CompanyDBDataContext();
Employee Employees = new Employee
{

Eno = Convert.ToInt32(textBox1.Text),
Ename = textBox2.Text,
Job = textBox3.Text,
Salary =Convert.ToInt32(textBox4.Text),
Dname = textBox5.Text
};
dc.Employees.InsertOnSubmit(Employees);
dc.SubmitChanges();
}

Modify Record using Linq


Private void button2_click(object sender, EventArgs e)

string connectString =
System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToSt
ring();

LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);

//Get Employee for update

Employee employee =
db.Employees.FirstOrDefault(e
=>e.Name.Equals("Michael"));
Textbox1.text=employee.Eno;
Textbox2.text=employee.Ename;

employee.Name = "George Michael";


employee.Email = "[email protected]";
employee.ContactNo = "99999999";
employee.DepartmentId = 2;
employee.Address = "Michael George - UK";

//Save changes to Database.


db.SubmitChanges();
}
Delete record using Linq to sql
Private void button2_click(object sender, EventArgs e)

string connectString =
System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnectionString"].ToSt
ring();

LinqToSQLDataContext db = newLinqToSQLDataContext(connectString);

//Get Employee to Delete


Employee deleteEmployee = db.Employees.FirstOrDefault(e ⇒e.Name.Equals("George Michael"));

//Delete Employee
db.Employees.DeleteOnSubmit(deleteEmployee);

//Save changes to Database.


db.SubmitChanges();
}

You might also like