Using LINQ to SQL in C# for Database Access
Q: How do you work with LINQ to SQL in C# to interact with a database?
- C#
- Mid level question
Explore all the latest C# interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create C# interview for FREE!
To work with LINQ to SQL in C#, you can follow these steps:
- Create
a database: First, create a database in SQL Server that you want to
interact with.
- Create
a LINQ to SQL data context: In your C# project, create a LINQ to SQL data
context by right-clicking the project in Solution Explorer and selecting
Add > New Item > Data > LINQ to SQL Classes. This will generate a
.dbml file, which you can use to map your database tables to classes in
your C# code.
- Add
tables to the data context: In the LINQ to SQL designer, drag and drop
tables from the database onto the design surface. This will create class
representations of the tables.
- Query
data: You can query data from the database using LINQ to SQL syntax, which
is similar to LINQ syntax. For example, to retrieve all records from a
table named "Customers", you can write the following code:
using (var context = new MyDataContext()) { var customers = from c in context.Customers select c; }
This will create a LINQ query that selects all records from
the Customers table and returns them as an IQueryable<Customer>
collection.
- Modify
data: You can modify data in the database using the generated classes. For
example, to update a record, you can retrieve it from the context, modify
its properties, and then call the SubmitChanges() method on the context to
save the changes to the database.
using (var context = new MyDataContext()) { var customer = (from c in context.Customers where c.CustomerID == "ALFKI" select c).Single(); customer.ContactName = "New Contact Name"; context.SubmitChanges(); }
This will retrieve a single record from the Customers table
where the CustomerID is "ALFKI", update its ContactName property, and
then save the changes to the database.
These are the basic steps to work with LINQ to SQL in C#.
LINQ to SQL provides a powerful and convenient way to interact with databases
in C# by using object-oriented syntax instead of raw SQL queries.


