Welcome!

Microsoft Cloud Authors: Pat Romanski, Andreas Grabner, Nick Basinger, Kevin Benedict, Liz McMillan

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
Moroccanoil®, the global leader in oil-infused beauty, is thrilled to announce the NEW Moroccanoil Color Depositing Masks, a collection of dual-benefit hair masks that deposit pure pigments while providing the treatment benefits of a deep conditioning mask. The collection consists of seven curated shades for commitment-free, beautifully-colored hair that looks and feels healthy.
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
The textured-hair category is inarguably the hottest in the haircare space today. This has been driven by the proliferation of founder brands started by curly and coily consumers and savvy consumers who increasingly want products specifically for their texture type. This trend is underscored by the latest insights from NaturallyCurly's 2018 TextureTrends report, released today. According to the 2018 TextureTrends Report, more than 80 percent of women with curly and coily hair say they purcha...
We all love the many benefits of natural plant oils, used as a deap treatment before shampooing, at home or at the beach, but is there an all-in-one solution for everyday intensive nutrition and modern styling?I am passionate about the benefits of natural extracts with tried-and-tested results, which I have used to develop my own brand (lemon for its acid ph, wheat germ for its fortifying action…). I wanted a product which combined caring and styling effects, and which could be used after shampo...
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
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...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.