Welcome!

Microsoft Cloud Authors: Andreas Grabner, Nick Basinger, Kevin Benedict, Pat Romanski, 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
Tapping into blockchain revolution early enough translates into a substantial business competitiveness advantage. Codete comprehensively develops custom, blockchain-based business solutions, founded on the most advanced cryptographic innovations, and striking a balance point between complexity of the technologies used in quickly-changing stack building, business impact, and cost-effectiveness. Codete researches and provides business consultancy in the field of single most thrilling innovative te...
CloudEXPO has been the M&A capital for Cloud companies for more than a decade with memorable acquisition news stories which came out of CloudEXPO expo floor. DevOpsSUMMIT New York faculty member Greg Bledsoe shared his views on IBM's Red Hat acquisition live from NASDAQ floor. Acquisition news was announced during CloudEXPO New York which took place November 12-13, 2019 in New York City.
With the introduction of IoT and Smart Living in every aspect of our lives, one question has become relevant: What are the security implications? To answer this, first we have to look and explore the security models of the technologies that IoT is founded upon. In his session at @ThingsExpo, Nevi Kaja, a Research Engineer at Ford Motor Company, discussed some of the security challenges of the IoT infrastructure and related how these aspects impact Smart Living. The material was delivered interac...
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...
Intel is an American multinational corporation and technology company headquartered in Santa Clara, California, in the Silicon Valley. It is the world's second largest and second highest valued semiconductor chip maker based on revenue after being overtaken by Samsung, and is the inventor of the x86 series of microprocessors, the processors found in most personal computers (PCs). Intel supplies processors for computer system manufacturers such as Apple, Lenovo, HP, and Dell. Intel also manufactu...
Darktrace is the world's leading AI company for cyber security. Created by mathematicians from the University of Cambridge, Darktrace's Enterprise Immune System is the first non-consumer application of machine learning to work at scale, across all network types, from physical, virtualized, and cloud, through to IoT and industrial control systems. Installed as a self-configuring cyber defense platform, Darktrace continuously learns what is ‘normal' for all devices and users, updating its understa...
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...
Apptio fuels digital business transformation. Technology leaders use Apptio's machine learning to analyze and plan their technology spend so they can invest in products that increase the speed of business and deliver innovation. With Apptio, they translate raw costs, utilization, and billing data into business-centric views that help their organization optimize spending, plan strategically, and drive digital strategy that funds growth of the business. Technology leaders can gather instant recomm...
OpsRamp is an enterprise IT operation platform provided by US-based OpsRamp, Inc. It provides SaaS services through support for increasingly complex cloud and hybrid computing environments from system operation to service management. The OpsRamp platform is a SaaS-based, multi-tenant solution that enables enterprise IT organizations and cloud service providers like JBS the flexibility and control they need to manage and monitor today's hybrid, multi-cloud infrastructure, applications, and wor...
The Master of Science in Artificial Intelligence (MSAI) provides a comprehensive framework of theory and practice in the emerging field of AI. The program delivers the foundational knowledge needed to explore both key contextual areas and complex technical applications of AI systems. Curriculum incorporates elements of data science, robotics, and machine learning-enabling you to pursue a holistic and interdisciplinary course of study while preparing for a position in AI research, operations, ...