How to Use LINQ to SQL in C Sharp
Part 1 of 6:
Setting Up
- Create or open a C# program in Visual Studio. The example uses the Console Application template.
- Right click on your program in Solution Explorer.
- Click Add Reference...
- Under .NET, select System.Data.Linq
- Click OK
- Add the following lines to the top of the source code:
using System.Linq; using System.Data.Linq; using System.Data.Linq.Mapping;
- Note: Visual Studio may have already added the line for System.Linq.
- Create a new DataContext class by entering this code, replacing login_string with your actual login string:
class MyDatabase : DataContext { private const String LoginString = "login_string"; public MyDatabase() : base(LoginString) { } }
- Add this line to your Main method to create a new instance of the MyDatabase class:
MyDatabase db = new MyDatabase();
- The DataContext instance acts as your connection to SQL Server.
Part 2 of 6:
Creating a New Table
- Add this line your Main method to create a new table in your database:
db.ExecuteCommand("Create table employees. (ID int, Name varchar(50), Department varchar(50))");
- Other SQL commands may be issued in a similar manner, by passing the command string to ExecuteCommand.
- Add the follow line to finalize the changes to the database:
db.SubmitChanges();
Part 3 of 6:
Associating a Table with a Class
- Add these lines to your source code:
[Table(Name = "Employees")] public class Employee { [Column(IsPrimaryKey = true)] public int ID; [Column] public string Name; [Column] public string Department; }
- This will define a new class, with the Table attribute indicating that the class represents table data, the Name parameter associating a name for that table, the Column attribute indicating column names and types, and the IsPrimaryKey parameter indicating the primary key column.
Part 4 of 6:
Inserting Data to the Database
- Add this line to the MyDatabase class:
public Table<Employee> Employees;
- In your Main method, create three new rows of data with new instances of the Employee class and filling in the data, as follows:
Employee employee1 = new Employee(); employee1.ID = 101; employee1.Name = "John Smith"; employee1.Department = "Sales"; db.Employees.InsertOnSubmit(employee1); Employee employee2 = new Employee(); employee2.ID = 102; employee2.Name = "Ted Black"; employee2.Department = "Research"; db.Employees.InsertOnSubmit(employee2); Employee employee3 = new Employee(); employee3.ID = 103; employee3.Name = "Allen Gottlieb"; employee3.Department = "Sales"; db.Employees.InsertOnSubmit(employee3); db.SubmitChanges();
Part 5 of 6:
Querying the Database
- Know that querying the database can be done within your source code using a syntax which is similar to SQL.
- To access the data for everyone in sales, and display their names and ID numbers, use the following lines:
var salesDept = from e in db.Employees where e.Department == "Sales" select e; foreach(var employee in salesDept) Console.WriteLine(employee.Name + " " + employee.ID);
- Similar queries can be made using similar code. For instance, to get and display Ted Black's ID number, you could use this code:
var queryResult = from e in db.Employees where e.Name == "Ted Black" select e; var tedBlack = queryResult.First(); Console.WriteLine(tedBlack.ID);
Part 6 of 6:
Summary
- Look at the whole thing. This is the entire program shown above. It connects to SQL server, creates a new table, adds a few new entries to that table, then queries some of the data.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.Linq; using System.Data.Linq.Mapping; namespace ConsoleApplication1 { [Table(Name = "Employees")] public class Employee { [Column(IsPrimaryKey = true)] public int ID; [Column] public string Name; [Column] public string Department; } class MyDatabase : DataContext { private const String LoginString = "login_string"; public Table<Employee> Employees; public MyDatabase() : base(LoginString) { } } class Program { static void Main(string[] args) { MyDatabase db = new MyDatabase(); db.ExecuteCommand("CREATE TABLE Employees (ID int, Name varchar(50), Department varchar(50))"); Employee employee1 = new Employee(); employee1.ID = 101; employee1.Name = "John Smith"; employee1.Department = "Sales"; db.Employees.InsertOnSubmit(employee1); Employee employee2 = new Employee(); employee2.ID = 102; employee2.Name = "Ted Black"; employee2.Department = "Research"; db.Employees.InsertOnSubmit(employee2); Employee employee3 = new Employee(); employee3.ID = 103; employee3.Name = "Allen Gottlieb"; employee3.Department = "Sales"; db.Employees.InsertOnSubmit(employee3); db.SubmitChanges(); var salesDept = from e in db.Employees where e.Department == "Sales" select e; foreach(var employee in salesDept) Console.WriteLine(employee.Name + " " + employee.ID); var queryResult = from e in db.Employees where e.Name == "Ted Black" select e; var tedBlack = queryResult.First(); Console.WriteLine(tedBlack.ID); } } }
3.5 ★ | 2 Vote
You should read it
- AI causes 10,000 telecommunications workers in the UK to lose their jobs
- 6 types of bosses make any good employee want to 'run'
- How to Prepare Payroll in Excel
- TEMPORARY TABLE temporary table in SQL
- How to retain good employees?
- Visit the tree office that Microsoft makes employees, chatting, working or sunbathing
- CLONE TABLE in SQL
- Steps to create graphs (charts) in Excel
May be interested
- eQuiz - Multiple choice test on C # - part 2we will continue with part 2 of the small test series on c #, there will be 15 questions in total with no time to answer each sentence.
- Understanding Plasmacluster ion technology on Sharp air purifier what's special?one of the outstanding technologies of sharp air purifiers is the plasmacluster ion. and to better understand this technology, please refer to the sharing below!
- How to sharpen a standard knife as an expert?whether you are looking to cook a basic healthy meal or learn how to present a platter of delicious dishes, we will provide you with the basics of getting into the kitchen. but first start with the most important tool in the kitchen: it's a knife.
- How to compress images in Node.js using Sharpcompressing images for the web or in apps can greatly improve performance. sharp will help you compress images in node.js easily.
- After Foxconn, it was Sharp's turn to mass produce masks in super-clean roomsthe japanese electronics maker plans to create 150,000 masks a day on demand from the government.
- Two new laptops from Sharpjapanese electronics firm sharp introduced two new pc-cw60x and pc-cw50x notebooks with a slim and compact design. the two models have similar specifications except for pc-cw60x which supports the ability to watch digital television
- PC-Z1 - miniature netbooksharp netwalker pc-z1 is a ultra-portable internet access device, designed as a netbook, but the screen is only 5 inches.
- KURT function - The function returns the sharp coefficient of a dataset in Exceldescription: the function returns the sharp coefficient of the dataset. kurtosis indicates the sharp or flat characteristics of a dataset. - if the coefficient is positive - the distribution is relatively pointed. - if the negative coefficient is negative - the distribution is relatively flat. syntax: kurt (number1, [number2], ...)
- 4 ways to make blurry photos sharpwhether you're an aspiring photographer, an instagrammer, or just someone who likes to hoard photos in your collection, knowing how to fix blurry photos is a skill you'll find very useful to have. okay.
- Which brand electric thermos should you buy best?sharp, sunhouse, panasonic are the 3 best hydroelectric brands in the market. take a look at the following article to find out what hydroelectricity panasonic, sunhouse and sharp have advantages and disadvantages.