Welcome!

Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

Related Topics: Microsoft Cloud, Silverlight

Microsoft Cloud: Article

A Nice Clean Way to Model Your Application's Data Layer

Using LINQ-to-SQL (Part 1)

Over the last few months I've written a series of blog posts that covered some of the new language features that are coming with the Visual Studio and .NET Framework Orcas release. Here are pointers to those posts:

  • Automatic Properties, Object Initializer and Collection Initializers
  • Extension Methods
  • Lambda Expressions
  • Query Syntax
  • Anonymous Types
The language features above help make querying data a first-class programming concept. We call this overall querying programming model LINQ, which stands for .NET Language Integrated Query.

Developers can use LINQ with any data source. They can express efficient query behavior in their programming language of choice, optionally transform/shape data query results into whatever format they want, and then easily manipulate the results. LINQ-enabled languages can provide full type-safety and compile-time checking of query expressions, and development tools can provide full intellisense, debugging, and rich refactoring support when writing LINQ code.

LINQ supports a very rich extensibility model that facilitates the creation of efficient domain-specific operators for data sources. The Orcas version of the .NET Framework ships with built-in libraries that enable LINQ support against objects, XML, and databases.

What Is LINQ-to-SQL?
LINQ-to-SQL is an O/RM (object/relational mapping) implementation that ships in the .NET Framework Orcas release, and lets you model a relational database using .NET classes. You can then query the database using LINQ, as well as update/insert/delete data from it.

LINQ-to-SQL fully supports transactions, views, and stored procedures. It also provides an easy way to integrate data validation and business logic rules into your data model.

Modeling Databases Using LINQ to SQL
Orcas ships with a LINQ-to-SQL designer that provides an easy way to model and visualize a database as a LINQ-to-SQL object model. My next article will cover in more depth how to use this designer (you can also watch this video I made in January to see me build a LINQ-to-SQL model from scratch using it).

Using the LINQ-to-SQL designer I can easily create a representation like the Northwind sample database below: (Figure 1)

My LINQ-to-SQL design-surface above defines four entity classes: Product, Category, Order, and OrderDetail. The properties of each class map to the columns of a corresponding table in the database. Each instance of a class entity represents a row in the database table. (Figure 2)
The arrows between the four entity classes above represent associations/relationships between the different entities. These are typically modeled using primary-key/foreign-key relationships in the database. The direction of the arrows on the design-surface indicate whether the association is a one-to-one or one-to-many relationship. Strongly-typed properties will be added to the entity classes based on this. For example, the Category class above has a one-to-many relationship with the Product class. This means it will have a Categories property, which is a collection of Product objects in that category. The Product class then has a Categoryproperty that points to a Category class instance that represents the Category to which the Product belongs.

The right-hand method pane in the LINQ-to-SQL design surface above contains a list of stored procedures that interact with our database model. In the sample above I added a single "GetProductsByCategory" SPROC. It takes a categoryID as an input argument and returns a sequence of Product entities as a result. We'll look at how to call this SPROC in a code sample below.

Understanding the DataContext Class
When you press the "save" button in the LINQ-to-SQL designer surface, Visual Studio will persist the .NET classes that represent the entities and database relationships that we modeled. For each LINQ-to-SQL designer file added to our solution, a custom DataContext class will also be generated. This DataContext class is the main conduit by which we'll query entities from the database as well as apply changes. The DataContext class created will have properties that represent each Table we modeled in the database, as well as methods for each Stored Procedure we added.

For example, below is the NorthwindDataContext class that is persisted based on the model we designed above:

LINQ-to-SQL Code Examples
Once we've modeled our database using the LINQ-to-SQL designer, we can then easily write code to work against it. Below are a few code examples that show off common data tasks:

1)  QUERY PRODUCTS FROM THE DATABASE
The code below uses LINQ query syntax to retrieve an IEnumerable sequence of Product objects. Note how the code is querying across the Product/Category relationship to retrieve only those products in the "Beverages" category.

 

More Stories By Scott Guthrie

Scott Guthrie, who will be keynoting October 20, 2008, was a founding member of the .NET Framework team and today runs the development teams that deliver the CLR, ASP.NET, Silverlight, WPF, IIS7, and the Visual Studio tools for web, WPF and Silverlight development. Previously the General Manager of Microsoft's Developer Division, he was promoted to Corporate Vice President in February '08.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
Atmosera delivers modern cloud services that maximize the advantages of cloud-based infrastructures. Offering private, hybrid, and public cloud solutions, Atmosera works closely with customers to engineer, deploy, and operate cloud architectures with advanced services that deliver strategic business outcomes. Atmosera's expertise simplifies the process of cloud transformation and our 20+ years of experience managing complex IT environments provides our customers with the confidence and trust tha...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility. As they do so, IT professionals are also embr...
In his general session at 19th Cloud Expo, Manish Dixit, VP of Product and Engineering at Dice, discussed how Dice leverages data insights and tools to help both tech professionals and recruiters better understand how skills relate to each other and which skills are in high demand using interactive visualizations and salary indicator tools to maximize earning potential. Manish Dixit is VP of Product and Engineering at Dice. As the leader of the Product, Engineering and Data Sciences team at D...
As you know, enterprise IT conversation over the past year have often centered upon the open-source Kubernetes container orchestration system. In fact, Kubernetes has emerged as the key technology -- and even primary platform -- of cloud migrations for a wide variety of organizations. Kubernetes is critical to forward-looking enterprises that continue to push their IT infrastructures toward maximum functionality, scalability, and flexibility.
Today's workforce is trading their cubicles and corporate desktops in favor of an any-location, any-device work style. And as digital natives make up more and more of the modern workforce, the appetite for user-friendly, cloud-based services grows. The center of work is shifting to the user and to the cloud. But managing a proliferation of SaaS, web, and mobile apps running on any number of clouds and devices is unwieldy and increases security risks. Steve Wilson, Citrix Vice President of Cloud,...