LINQ to SQL with MVC 3.0 – Sample Project

LINQ – Linq stands for Language Integrated Query .Linq is a Microsoft .Net framework Component. Linq can be used to Query any kind of Data Source like collection of objects,Database or XML.It can retrieve data from any objects that implements the IEnumerable<T> interface.
Linq is divided in three areas.
1) LINQ to Object
2) LINQ to ADO.Net
  • LINQ to SQL
  • LINQ to Entities
  • LINQ to Dataset
3) LINQ to XML
Lets discuss LINQ to SQL here
LINQ to SQL – LINQ to SQL supports LINQ query against the relational database for data retrieval and manipulation. LINQ to SQL is used for managing relational Data as objects.LINQ to SQL translated the LINQ query and send it to database for Execution and once result is returned it translated result back to the objects to be used in the Application. We can validate the LINQ query using IntelliSense.
Add an ASP.NET MVC 3 Web Application from Project Template
Select Internet Application – Select the View Engine (Razor / — Both have different Syntax, i selected Select the HTML5 markup if you want to use HTML 5 – This will create a MVC 3 web application with Default Folder Structure , Views ,Controllers etc

Right Click on Models Folder and Click to Add a New Item

Select to Add LINQ to SQL Classes and give a name to .dbml file

Double Click on the .dbml file created , that will open the above interface , on the Right Hand Side , there is a Server Explorer Tab . From There you can Access your existing Database like SQL database or Add a new Data Connection using Data Connection/Add New  Connection.

This is the place to Database Connection Details Like Server Name/Address  , Authentication details etc

Once the DataConnection is Added, we can see all the Tables in the Database.
Drag all the tables from the Server Explorer to the Window, it shows the tables and  the relations  , Click Save – Which Creates the corresponsind classes

This shows the various classes created – of all the classes created for the corresponding tables the DataContext class is the main conduit by which we’ll query entities from thedatabase as well as apply changes back to it. It contains various flavors of types and constructors, partial validation methods, and property members for all the included tables
To query a database using LINQ to SQL, we first need to construct a DataContext object,
TechnologixsDataContext db = new TechnologixsDataContext();
Then we can use this LINQ query syntax to retrieve records from the database
IQueryable<string> myName = from p in Db.DbUsers select p.login;

The data stored in the ViewBag is displayed with the <%  %>  in the view
Final Output

No Comments Yet.

Leave a comment