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

Using Using Using: Args Context

The code connects to a SQL database using LINQ, retrieves a list of departments, adds a new department, updates the name of an existing department, deletes a department, and retrieves an updated list of departments to display the changes made to the database. It demonstrates basic CRUD (create, read, update, delete) operations using LINQ to perform queries and modify data in a SQL database.

Uploaded by

Secu Camelia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Using Using Using: Args Context

The code connects to a SQL database using LINQ, retrieves a list of departments, adds a new department, updates the name of an existing department, deletes a department, and retrieves an updated list of departments to display the changes made to the database. It demonstrates basic CRUD (create, read, update, delete) operations using LINQ to perform queries and modify data in a SQL database.

Uploaded by

Secu Camelia
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

using DataAccess;

using System;

using System.Linq;

namespace LINQTOSQLConsoleApp {

public class LinqToEntityModel {

static void Main(string[] args) {

using (LinqToSQLDBEntities context = new LinqToSQLDBEntities()) {

//Get the List of Departments from Database

var departmentList = from d in context.Departments

select d;

foreach (var dept in departmentList) {

Console.WriteLine("Department Id = {0} , Department Name = {1}",

dept.DepartmentId, dept.Name);

//Add new Department

DataAccess.Department department = new DataAccess.Department();

department.Name = "Support";

context.Departments.Add(department);

context.SaveChanges();

Console.WriteLine("Department Name = Support is inserted in Database");

//Update existing Department

DataAccess.Department updateDepartment = context.Departments.FirstOrDefault(d


⇒d.DepartmentId == 1);

updateDepartment.Name = "Account updated";


context.SaveChanges();

Console.WriteLine("Department Name = Account is updated in Database");

//Delete existing Department

DataAccess.Department deleteDepartment = context.Departments.FirstOrDefault(d


⇒d.DepartmentId == 3);

context.Departments.Remove(deleteDepartment);

context.SaveChanges();

Console.WriteLine("Department Name = Pre-Sales is deleted in Database");

//Get the Updated List of Departments from Database

departmentList = from d in context.Departments

select d;

foreach (var dept in departmentList) {

Console.WriteLine("Department Id = {0} , Department Name = {1}",

dept.DepartmentId, dept.Name);

Console.WriteLine("\nPress any key to continue.");

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result −

You might also like