Jan 24

Once again Microsoft brings some knowledge to the masses :) This time its free e-books. All the headings speak for them selfs and with few words these books are MUST HAVE for every developer. Only few chapters are included in pdf’s as you are encouraged to buy them! Here is the content:

ms_linq_cvr.jpgIntroducing Microsoft LINQ
by Paolo Pialorsi and Marco Russo

ISBN: 9780735623910

* Chapter 1: LINQ Introduction
* Chapter 2: C# Language Features
* Chapter 3: Visual Basic 9.0 Language Features
* Chapter 4: LINQ Syntax Fundamentals
* Chapter 5: LINQ to ADO.NET
* Chapter 6: LINQ to XML

ms_ajax_cvr.jpgIntroducing Microsoft ASP.NET AJAX
by Dino Esposito

ISBN: 9780735624139

* Chapter 1: The AJAX Revolution
* Chapter 5: The AJAX Control Toolkit

ms_silverlight_cvr.jpgIntroducing Microsoft Silverlight 1.0
by Laurence Moroney

ISBN: 9780735625396

* Chapter 1: Silverlight and User Experience
* Chapter 5: Programming Silverlight with JavaScript

Log into Microsoft Press home page for more info here
Dec 04

Bill Horst continues with those simple examples. After this one here comes the other set. They are perfect to show basic syntax. Here are few more:

DISTINCT
SQL SELECT statements can include the DISTINCT specifier, which causes all duplicate records in the query result to be removed. In a LINQ expression, Distinct is its own individual clause, rather than a specifier on the Select clause. This means that Distinct can appear between any two other clauses. The Distinct clause takes whatever result is returned by the preceding clause (Select, in the case below) and returns a filtered result with duplicates removed. To two code examples below accomplish the same results:

SQL

SELECT DISTINCT Name, Address
FROM CustomerTable

VB

From Contact In CustomerTable _
Select Contact.Name, Contact.Address _
Distinct

ORDER BY
The SQL ORDER BY clause can also be represented in a LINQ expression. A LINQ Order By clause allows for a comma-delimited list of expressions to specify how results should be sorted. Any valid VB expression can be used, so these expressions don’t necessarily have to be the names of field that were selected.

SQL

SELECT * FROM CustomerTable
ORDER BY Phone

VB

From Contact In CustomerTable _
Order By Contact.Phone

ASC/DESC
A SQL ORDER BY clause can also include ASC and DESC keywords, to specify that the sort should be in ascending or descending order, respectively. VB uses Ascending and Descending keywords for the same purpose, with the same syntax. If neither specifier is present, ascending order is the default.

SQL

SELECT * FROM CustomerTable
ORDER BY Phone ASC, Name DESC

VB

From Contact In CustomerTable _
Order By Contact.Phone Ascending, Contact.Name Descending

Here is the original post by Bill Horst

Dec 03

This is a series of posts regarding the new language improvements in VB 9. Bill Horst has written the second on which I came across here. As we all know VB LINQ statements enable SQL-like syntax for queries in the VB language. LINQ syntax doesn’t match SQL syntax exactly, so if you are already working with SQL or familiar with SQL queries, you may find yourself wanting to convert an existing SQL query to LINQ.

And here is an example with FROM clause:

A SQL SELECT statement always begins with a SELECT Clause, followed by a FROM Clause. A VB query expression always begins with a From Clause or Aggregate Clause (Aggregate will be discussed later). A basic SQL FROM clause specifies a table over which to query, and similarly, a LINQ From Clause specifies an object over which to query (CustomerTable). This object could represent “In-Memory” data, a SQL data table, or XML information. My examples use the “In-Memory” case, since it allows the simplest code. In addition to this data object, the VB From clause always includes an identifier for the current “row” (Contact), which basically functions as an alias.

SQL

SELECT Contact.CustomerID, Contact.Phone
FROM CustomerTable Contact

LINQ

From Contact In CustomerTable
Select Contact.CustomerID, Contact.Phone

Here is the whole post by Bill Horst.

Nov 19

Today Microsoft shipped Visual Studio 2008 and .NET 3.5. You can download the final release using one of the links below:

* If you are a MSDN subscriber, you can download your copy from the MSDN subscription site (note: some of the builds are just finishing being uploaded now - so check back later during the day if you don’t see it yet).

* If you are a non-MSDN subscriber, you can download a 90-day free trial edition of Visual Studio 2008 Team Suite here. A 90-day trial edition of Visual Studio 2008 Professional (which will be a slightly smaller download) will be available next week. A 90-day free trial edition of Team Foundation Server can also be downloaded here.

*If you want to use the free Visual Studio 2008 Express editions (which are much smaller and totally free), you can download them here.

* If you want to just install the .NET Framework 3.5 runtime, you can download it here.

List of New Features - old version

- VS 2008 Multi-Targeting Support
VS 2008 enables you to build applications that target multiple versions of the .NET Framework. This means you can use VS 2008 to open, edit and build existing .NET 2.0 and ASP.NET 2.0 applications (including ASP.NET 2.0 applications using ASP.NET AJAX 1.0), and continue to deploy these application on .NET 2.0 machines.

- ASP.NET AJAX and JavaScript Support
.NET 3.5 has ASP.NET AJAX built-in (no separate download required). In addition to including all of the features in ASP.NET AJAX 1.0, ASP.NET 3.5 also now includes richer support for UpdatePanels integrating with WebParts, ASP.NET AJAX integration with controls like and , WCF support for JSON, and many other AJAX improvements.

- VS 2008 Web Designer and CSS Support
VS 2008 and Visual Web Developer 2008 Express includes a significantly improved HTML web designer (the same one that ships with Expression Web). This delivers support for split-view editing, nested master pages, and great CSS integration.

- Language Improvements and LINQ
The new VB and C# compilers in VS 2008 deliver significant improvements to the languages. Both add functional programming concepts that enable you to write cleaner, terser, and more expressive code. These features also enable a new programming model we call LINQ (language integrated query) that makes querying and working with data a first-class programming concept with .NET.

- Data Access Improvements with LINQ to SQL
LINQ to SQL is a built-in OR/M (object relational mapper) in .NET 3.5. It enables you to model relational databases using a .NET object model. 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 business logic and validation rules into your data model.

- Browsing the .NET Framework Library Source using Visual Studio

Lots of other improvements

The list above is only a small set of the improvements coming. For client development VS 2008 includes WPF designer and project support. ClickOnce and WPF XBAPs now work with FireFox. WinForms and WPF projects can also now use the ASP.NET Application Services (Membership, Roles, Profile) for roaming user data.

Office development is much richer - including support for integrating with the Office 2007 ribbon, and with Outlook. Visual Studio Tools for Office support is also now built-into Visual Studio (you no longer need to buy a separate product).

New WCF and Workflow projects and designers are now included in VS 2008. Unit testing support is now much faster and included in VS Professional (and no longer just VSTS). Continuous Integration support is now built-in with TFS. AJAX web testing (unit and load) is now supported in the VS Test SKU. And there is much, much more…

Installation Suggestions

People often ask me for suggestions on how best to upgrade from previous betas of Visual Studio 2008. In general I’d recommend uninstalling the Beta2 bits explicitly. As part of this you should uninstall Visual Studio 2008 Beta2, .NET Framework Beta2, as well as the Visual Studio Web Authoring Component (these are all separate installs and need to be uninstalled separately). I then usually recommend rebooting the machine after uninstalling just to make sure everything is clean before you kick off the new install. You can then install the final release of VS 2008 and .NET 3.5 on the machine.

Once installed, I usually recommend explicitly running the Tools->Import and Export Settings menu option, choosing the “Reset Settings” option, and then re-pick your preferred profile. This helps ensure that older settings from the Beta2 release are no longer around (and sometimes seems to help with performance).

Note that VS 2008 runs side-by-side with VS 2005 - so it is totally fine to have both on the same machine (you will not have any problems with them on the same box).

Silverlight Tools and VS Web Deployment Project Add-Ins

Two popular add-ins to Visual Studio are not yet available to download for the final VS 2008 release. These are the Silverlight 1.1 Tools Alpha for Visual Studio and the Web Deployment Project add-in for Visual Studio. Our hope is to post updates to both of them to work with the final VS 2008 release in the next two weeks. If you are doing Silverlight 1.1 development using VS 2008 Beta2 you’ll want to stick with with VS 2008 Beta2 until this updated Silverlight Tools Add-In is available.

Read Scott Gu

Aug 26

Наскоро Microsoft представиха последните версии на Visual Studio 2008 и .NET 3.5 beta 2. Visual Studio 2008 можете да изтеглите от тук, а умалената експрес версия от тук. Важно е да отблежим, че новите версии можете да инсталирате съвместно с по-старата VS 2005.

Ето и някои от последните нововъведения в Visual Studio 2008:

- Поддръжка на Multi-Targeting – VS 2008 ви дава възможност да създавате приложения предназначени за различни версии на .NET Framework. Лесно може да се превключва от една версия на друга.

- VS 2008 Web Designer и поддръжка на CSS – в тази версия е включен подобрен HTML web designer. В него се поддържат ‘двоен’(сплит) изглед, внедрени една в друга master pages, и подобрена CSS поддръжка.

- ASP.NET AJAX и поддръжка на JavaScript – в .NET 3.5, ASP.NET AJAX е внедрен, както и са добавени нови функционалности като UpdatePanel с WebParts, поддръжка на WCF за JSON, и редица други подобрения по бързодействието. VS 2008 има и увеличена поддръжка относно интегрирането на JavaScript и AJAX в приложенията. Новото студио се отличава с подобрен Intellisense, който дори работи при включени външни JavaScript файлове.

- Езикови подобрения и LINQ – новите компилатори на VB и C# имат доста подобрения относно функциите на езиците. Това основно се забелязва при LINQ(language integrated query) който добавя нови възможности при заявки и работа с данни. Ето и някой от подобренията налични в C#:
o Automatic Properties, Object Initializer and Collection Initializers
o Extension Methods
o Lambda Expressions
o Query Syntax
o Anonymous Types

- Подобрен достъп до данни чрез LINQ към SQL
LINQ към SQL е внедрен OR/M (object relational mapper) в .NET 3.5. Той ви дава възможност да правите заявки чрез LINQ, както и да редактирате/изтривате и вмъквате нови записи. LINQ към SQL напълно поддържа транзакции, изгледи и запазени процедури.

Това са само някои от многото подобрения представени в новата версия. Дотук всичко е добре, но лично за мен остават отворени въпросите:
- Ще успеят ли да разработят всичките езикови подобрения и за Visual Basic?
- Ще успеят ли до Февруари 2008 да са готови с крайната версия?

Aug 07

Here is latest post from ScottGu’s blog. There he describes how to build a custom RSS Feed Reader using LINQ to XML. Check it out:

One of the big programming model improvements being made in .NET 3.5 is the work being done to make querying data a first class programming concept. We call this overall querying programming model “LINQ”, which stands for .NET Language Integrated Query.

LINQ supports a rich extensibility model that facilitates the creation of efficient domain-specific providers for data sources. .NET 3.5 ships with built-in libraries that enable LINQ support against Objects, XML, and Databases.


What is LINQ to XML?

LINQ to XML is a built-in LINQ data provider that is implemented within the “System.Xml.Linq” namespace in .NET 3.5.

LINQ to XML provides a clean programming model that enables you to read, construct and write XML data. You can use LINQ to XML to perform LINQ queries over XML that you retrieve from the file-system, from a remote HTTP URL or web-service, or from any in-memory XML content.

LINQ to XML provides much richer (and easier) querying and data shaping support than the low-level XmlReader/XmlWriter API in .NET today. It also ends up being much more efficient (and uses much less memory) than the DOM API that XmlDocument provides.


Using LINQ to XML to query a local XML File

To get a sense of how LINQ to XML works, we can create a simple XML file on our local file-system like below that uses a custom schema we’ve defined to store RSS feeds:

I could then use the new XDocument class within the System.Xml.Linq namespace to open and query the XML document above. Specifically, I want to filter the elements in the XML file and return a sequence of the non-disabled RSS feeds (where a disabled feed is a element with a “status” attribute whose value is “disabled”). I could accomplish this by writing the code below:

VB:

read whole article

Jul 18

Hi all, I have been quite busy lately so didnt got much time to post here, but now will try to catch it up. Here is a post from Scott Guthrie which is PART 5 of his LINQ to SQL series:

Over the last few weeks I’ve been writing a series of blog posts that cover LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapper) that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes. You can use LINQ expressions to query the database with them, as well as update/insert/delete data.

Below are the first four parts of my LINQ to SQL series:

In these previous LINQ to SQL blog posts I focused on how you can programmatically use LINQ to SQL to easily query and update data within a database.

In today’s blog post I’ll cover the new control that is shipping as part of ASP.NET in the upcoming .NET 3.5 release. This control is a new datasource control for ASP.NET (like the ObjectDataSource and SQLDataSource controls that shipped with ASP.NET 2.0) which makes declaratively binding ASP.NET UI controls to LINQ to SQL data models super easy.


Sample Application We’ll be Building

The simple data editing web application I’ll walkthrough building in this tutorial is a basic data entry/manipulation front-end for products within a database:

The application will support the following end-user features:

  1. Allow users to filter the products by category
  2. Allow users to sort the product listing by clicking on a column header (Name, Price, Units In Stock, etc)
  3. Allow users to skip/page over multiple product listings (10 products per page)
  4. Allow users to edit and update any of the product details in-line on the page
  5. Allow users to delete products from the list

The web application will be implemented with a clean object-oriented data model built using the LINQ to SQL ORM.

All of the business rules and business validation logic will be implemented in our data model tier - and not within the UI tier or in any of the UI pages. This will ensure that: 1) a consistent set of business rules are used everywhere within the application, 2) we write less code and don’t repeat ourselves, and 3) we can easily modify/adapt our business rules at a later date and not have to update them in dozens of different places across our application.

We will also take advantage of the built-in paging/sorting support within LINQ to SQL to ensure that features like the product listing paging/sorting are performed not in the middle-tier, but rather in the database (meaning only 10 products are retrieved from the database at any given time - we are not retrieving thousands of rows and doing the sorting/paging within the web-server).

read original

Jul 04

The third part from Scott Guthrie’s series LINQ to SQL:

Last month I started a blog post series covering LINQ to SQL. LINQ to SQL is a built-in O/RM (object relational mapping) framework that ships in the .NET Framework 3.5 release, and which enables you to easily model relational databases using .NET classes. You can then use LINQ expressions to query the database with them, as well as update/insert/delete data from it.

Below are the first two parts of my LINQ to SQL series:

In today’s blog post I’ll be going into more detail on how to use the data model we created in the Part 2 post, and show how to use it to query data within an ASP.NET project.


Northwind Database Modeled using LINQ to SQL

In Part 2 of this series I walked through how to create a LINQ to SQL class model using the LINQ to SQL designer that is built-into VS 2008. Below is the class model that we created for the Northwind sample database:


Retrieving Products

Once we have defined our data model classes above, we can easily query and retrieve data from our database. LINQ to SQL enables you to do this by writing LINQ syntax queries against the NorthwindDataContext class that we created using the LINQ to SQL designer above.

For example, to retrieve and iterate over a sequence of Product objects I could write code like below:

In the query above I have used a “where” clause in my LINQ syntax query to only return those products within a specific category. I am using the CategoryID of the Product to perform the filter.

One of the nice things above LINQ to SQL is that I have a lot of flexibility in how I query my data, and I can take advantage of the associations I’ve setup when modeling my LINQ to SQL data classes to perform richer and more natural queries against the database. For example, I could modify the query to filter by the product’s CategoryName instead of its CategoryID by writing my LINQ query like so:

Notice above how I’m using the “Category” property that is on each of the Product objects to filter by the CategoryName of the Category that the Product belongs to. This property was automatically created for us by LINQ to SQL because we modeled the Category and Product classes as having a many to one relationship with each other in the database.

read original

Jun 07

Introduction

Whenever someone asks me about the DataContext I always refer to it as the “brains” of Linq to SQL, why? Because it is. It is responsible for the translation of Linq to T-SQL, and the mapping of the results (rows) of that query to objects, and so much more.

If you run any codegen tool (SqlMetal, or Linq to SQL file (VS Orcas designer)) you always get a class that derives from the DataContext class. The DataContext can be equated to a database, in that it contains a series of tables (normally this is implemented as a property that returns a Table), and sprocs (methods calls that invoke underlying sprocs at the DB layer).

Note: The DataContext can also handle other SQL Server features like views, and table functions etc.

What’s so special about the DataContext class?

Most notably the DataContext takes some Linq code and generates the appropriate T-SQL statement for that query; if that query returns rows then the DataContext object will take care of mapping those rows to objects.

Figure 5-1: DataContext core functionality

I want to see the T-SQL generated by my LINQ

If you are a control freak/perfectionist like me then you probably want to know exactly what T-SQL is being generated for you at all times.

Before I show you some code please remember that the T-SQL generation by the DataContext object is not perfect, if you know of a very efficient T-SQL solution then implement that in a sproc. Saying that I have found the T-SQL generation of the DataContext object to be efficient in some advanced queries. Like so many things in programming one way, and one way alone is often not the best approach – experiment to see what offers the best performance for your query.

There are a few ways in which we can monitor the T-SQL being generated by our DataContext object, these include:

  • Visual Studio Orcas
  • ToString() override of query
  • DataContext Log property
  • SQL Server 2005 profiler (not included with Express edition)
Note: As the majority of people reading this article will be using the Express editions of the developer tools I will skip the SQL Server 2005 profiler demo. Those who have used the profiler before will know that it is a real time T-SQL dump of everything that a particular SQL Server 2005 instance is doing so seeing what T-SQL the DataContext is generating is a trivial task.

Visual Studio Orcas

As Linq is a 1st class citizen within the C# and VB.NET languages it should be no surprise to you whatsoever to see rich debugging support within the IDE.

Figure 5-2: Seeing the T-SQL generated by the DataContext object in VS Orcas

ToString() override

This is a really nice feature – if you call the ToString() method on any variable whose value is a query you can see the associated T-SQL for that query.

Figure 5-3: Calling ToString()

  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. namespace ConsoleApplication4
  5. {
  6. public class Program
  7. {
  8. public static void Main(string[] args)
  9. {
  10. using (BookShopDataContext db = new BookShopDataContext())
  11. {
  12. IEnumerable query = from b in db.Books select b;
  13. Console.WriteLine(query);
  14. }
  15. }
  16. }
  17. }


Figure 5-4: Result of running the code in Figure 5-3

Concurrency

Concurrency is always an issue – Linq to SQL by default uses optimistic concurrency. Take an example of where we retrieve a particular piece of data and then update that data, we then try to submit the updated data to the server but we get an exception as Linq to SQL knows that we have violated a concurrency check as we were acting upon “old” data.

Just to show this I did a pretty simple operation by adding a breakpoint on the line where I call the SubmitChanges(...) method and then executed some T-SQL code to alter that record and then continued the execution of my application so I would get an exception.

Figure 5-6: ChangeConflictException

The SubmitChanges(...) method is overrided to take a ConflictMode enum where we can change the default behaviour when data is submitted to the database, these are:

  • ContinueOnConflict
  • FailOnFirstConflict

The above can be used when within a TransactionScope. There are a few attribute values we can apply to our generated code to specifically say “we don’t care if this particular bit of data is changed – just overwrite it”. We do this using the UpdateCheck parameter to the Column attribute.

Figure 5-7: We don’t care about this data – just overwrite the value with what we have!

  1. [global::System.Data.Linq.Column(Storage=“_Title”, Name=“Title”,
  2. DBType=“NVarChar(50) NOT NULL”, CanBeNull=false,
  3. UpdateCheck=System.Data.Linq.UpdateCheck.Never)]

The UpdateCheck enum values:

  • Always
  • Never
  • WhenChanged

I’m pretty sure I’ve not covered everything in Linq to SQL with regards to concurrency – remember though that you can use the TransactionScope type in the .NET framework to assist you.

Using VS Orcas to look at data

Remember – queries only execute when we call the GetEnumerator() of the variable that holds the query! In previous CTP’s of VS Orcas it was hard to see what data we pulled back from the database as the debugger didn’t call the GetEnumerator() method when you wanted to look at that particular variable – the March CTP does however which is really great!

Let’s go ahead and look at using VS Orcas to look at data returned from our database using the Locals window when debugging. First place a breakpoint after the line you define a query, you don’t need a foreach to call the GetEnumerator() – the IDE will do that for us. When you get to your breakpoint you will see a screen similar to that in Figure 5-8 where the variable holding our query has a message saying something like “expand me to enumerate this IEnumerable”.

Figure 5-8: Thinking about enumerating the IEnumerable

Expand the results! You know you want to.

Figure 5-9: Viewing the results

You can see that in Figure 5-9 I have two objects returned from my query, I can drill down into the values of their properties and so forth.

On the face of it this is a pretty basic enhancement to the IDE, and you would be right in thinking so – but this is a great visual tool which I’m sure you will love when using Linq to SQL!

LINQ to SQL FAQ

Will LINQ to SQL support Oracle?

This is a common question, the answer to which is no. Linq to SQL is a lightweight O/R mapper targeted for use with SQL Server 2000/2005. For a more powerful O/R mapper look at the Entity Data Model (EDM) – EDM will support Oracle and other 3rd party databases.

I hate codegen tools, how much code does it really take to hook up to my DB using LINQ to SQL?

Surprisingly little, essentially you need to create a property with the correct access (get, set, or both?) with the appropriate Column attribute. The class with your properties should be pluralized and use the Table attribute to map it to the corresponding table in the database.

Finally you will need to create a class that derives from DataContext. In this class you will want to expose some properties that return a generic Table.

Below is the code for the TodoListDataContext and Task types:

Task.cs (type that is associated with records in Tasks):

  1. using System;
  2. using System.Data.Linq;
  3. namespace ConsoleApplication5
  4. {
  5. [Table(Name=“Tasks”)]
  6. public class Task
  7. {
  8. private int _taskId;
  9. [Column(Name = “TaskID”, Storage = “_taskId”,
  10. IsDBGenerated = true, IsPrimaryKey = true,
  11. CanBeNull = false, DBType = “int not null identity”)]
  12. public int TaskID
  13. {
  14. get { return _taskId; }
  15. }
  16. [Column(Name = “Title”, CanBeNull = false,
  17. DBType = “nvarchar(50) not null”)]
  18. public string Title
  19. {
  20. get;
  21. set;
  22. }
  23. [Column(Name = “Complete”, CanBeNull = false)]
  24. public bool Complete
  25. {
  26. get;
  27. set;
  28. }
  29. }
  30. }


TodoListDataContext.cs (type that exposes a Table of type Task, and defines connection string)

  1. using System;
  2. using System.Data.Linq;
  3. namespace ConsoleApplication5
  4. {
  5. public class TodoListDataContext : DataContext
  6. {
  7. public TodoListDataContext(string conn) : base(conn)
  8. {
  9. }
  10. public Table Tasks
  11. {
  12. get { return GetTable(); }
  13. }
  14. }
  15. }


Why are the changes to my data in SQL Server not being persisted?

Remember, in order to persist changes to SQL Server you need to call the SubmitChanges(...) method on your DataContext object after you have made changes to any data.

Can I use XML to define the O/R mapping?

Yes. You can use SqlMetal to generate an XML mapping file, when creating a DataContext you need to specify that your mapping is defined in an XML file by using the XmlMappingSource type.

I’m hitting the database every time for two identical queries, can I prevent this?

To prevent hitting the database every time you can load the results into memory (e.g. Append ToList() to a query) any subsequent calls to that query will use the in-memory collection rather than going off and querying the database again.

Is it possible to create code from XML?

Yes. You can create a .dbml file using SqlMetal and then generate a codefile (either VB.NET or CS) based on the XML defined in the .dbml.

What’s this deferred loading stuff?

Linq to SQL uses deferred loading when accessing properties of a related entity. Given a simple select query returning all Books, if I then want the publisher for each book then I can do so, however, behind the scenes the DataContext is doing a select where query to get the publisher for the current book. This is deferred loading.

Note: You can disable deferred loading using the EnableDeferredLoading property of a DataContext object.

Summary

There is a ton of stuff that’s special about the DataContext that I haven’t covered - I encourage everyone to go check out the DataContext class and experiment. I hope that I have provided you with the knowledge to get started with Linq, and Linq to SQL – if you have any questions about a particular feature of Linq to SQL I have/haven’t covered then please feel free to email me via the address on http://gbarnett.org/about.

read original

May 29

Another great article from Scott! Must read for all of us! Chech it out here:

In Part 1 of my LINQ to SQL blog post series I discussed “What is LINQ to SQL” and provided a basic overview of some of the data scenarios it enables.

In my first post I provided code samples that demonstrated how to perform common data scenarios using LINQ to SQL including:

  • How to query a database
  • How to update rows in a database
  • How to insert and relate multiple rows in a database
  • How to delete rows in a database
  • How to call a stored procedure
  • How to retrieve data with server-side paging

I performed all of these data scenarios using a LINQ to SQL class model that looked like the one below:

In this second blog post in the series I’m going to go into more detail on how to create the above LINQ to SQL data model.

LINQ to SQL, the LINQ to SQL Designer, and all of the features that I’m covering in this blog post series will ship as part of the .NET 3.5 and Visual Studio “Orcas” release.

You can follow all of the steps below by downloading either Visual Studio “Orcas” Beta 1 or Visual Web Developer Express “Orcas” Beta1. Both can be installed and used side-by-side with VS 2005.


Create a New LINQ to SQL Data Model

You can add a LINQ to SQL data model to an ASP.NET, Class Library or Windows client project by using the “Add New Item” option within Visual Studio and selecting the “LINQ to SQL” item within it:

Selecting the “LINQ to SQL” item will launch the LINQ to SQL designer, and allow you to model classes that represent a relational database. It will also create a strongly-typed “DataContext” class that will have properties that represent each Table we modeled within the database, as well as methods for each Stored Procedure we modeled. As I described in Part 1 of this blog post series, the DataContext class is the main conduit by which we’ll query entities from the database as well as apply changes back to it.

Below is a screen-shot of an empty LINQ to SQL ORM designer surface, and is what you’ll see immediately after creating a new LINQ to SQL data model:


Entity Classes

LINQ to SQL enables you to model classes that map to/from a database. These classes are typically referred to as “Entity Classes” and instances of them are called “Entities”. Entity classes map to tables within a database. The properties of entity classes typically map to the table’s columns. Each instance of an entity class then represents a row within the database table.

Entity classes defined with LINQ to SQL do not have to derive from a specific base class, which means that you can have them inherit from any object you want. All classes created using the LINQ to SQL designer are defined as “partial classes” - which means that you can optionally drop into code and add additional properties, methods and events to them.

Unlike the DataSet/TableAdapter feature provided in VS 2005, when using the LINQ to SQL designer you do not have to specify the SQL queries to use when creating your data model and access layer.

Instead, you focus on defining your entity classes, how they map to/from the database, and the relationships between them. The LINQ to SQL OR/M implementation will then take care of generating the appropriate SQL execution logic for you at runtime when you interact and use the data entities. You can use LINQ query syntax to expressively indicate how to query your data model in a strongly typed way.


Creating Entity Classes From a Database

If you already have a database schema defined, you can use it to quickly create LINQ to SQL entity classes modeled off of it.

The easiest way to accomplish this is to open up a database in the Server Explorer within Visual Studio, select the Tables and Views you want to model in it, and drag/drop them onto the LINQ to SQL designer surface:

When you add the above 2 tables (Categories and Products) and 1 view (Invoices) from the “Northwind” database onto the LINQ to SQL designer surface, you’ll automatically have the following three entity classes created for you based on the database schema:

Using the data model classes defined above, I can now run all of the code samples (expect the SPROC one) described in Part 1 of this LINQ to SQL series. I don’t need to add any additional code or configuration in order to enable these query, insert, update, delete, and server-side paging scenarios.


Naming and Pluralization

One of the things you’ll notice when using the LINQ to SQL designer is that it automatically “pluralizes” the various table and column names when it creates entity classes based on your database schema. For example: the “Products” table in our example above resulted in a “Product” class, and the “Categories” table resulted in a “Category” class. This class naming helps make your models consistent with the .NET naming conventions, and I usually find having the designer fix these up for me really convenient (especially when adding lots of tables to your model).

If you don’t like the name of a class or property that the designer generates, though, you can always override it and change it to any name you want. You can do this either by editing the entity/property name in-line within the designer or by modifying it via the property grid:

The ability to have entity/property/association names be different from your database schema ends up being very useful in a number of cases. In particular:

1) When your backend database table/column schema names change. Because your entity models can have different names from the backend schema, you can decide to just update your mapping rules and not update your application or query code to use the new table/column name.

2) When you have database schema names that aren’t very “clean”. For example, rather than use “au_lname” and “au_fname” for the property names on an entity class, you can just name them to “LastName” and “FirstName” on your entity class and develop against that instead (without having to rename the column names in the database).


Relationship Associations

When you drag objects from the server explorer onto the LINQ to SQL designer, Visual Studio will inspect the primary key/foreign key relationships of the objects, and based on them automatically create default “relationship associations” between the different entity classes it creates. For example, when I added both the Products and Categories tables from Northwind onto my LINQ to SQL designer you can see that a one to many relationship between the two is inferred (this is denoted by the arrow in the designer):

The above association will cause cause the Product entity class to have a “Category” property that developers can use to access the Category entity for a given Product. It will also cause the Category class to have a “Products” collection that enables developers to retrieve all products within that Category.

If you don’t like how the designer has modeled or named an association, you can always override it. Just click on the association arrow within the designer and access its properties via the property grid to rename, delete or modify it.


Delay/Lazy Loading

LINQ to SQL enables developers to specify whether the properties on entities should be prefetched or delay/lazy-loaded on first access. You can customize the default pre-fetch/delay-load rules for entity properties by selecting any entity property or association in the designer, and then within the property-grid set the “Delay Loaded” property to true or false.

For a simple example of when I’d want to-do this, consider the “Category” entity class we modeled above. The categories table inside “Northwind” has a “Picture” column which stores a (potentially large) binary image of each category, and I only want to retrieve the binary image from the database when I’m actually using it (and not when doing a simply query just to list the category names in a list).

I could configure the Picture property to be delay loaded by selecting it within the LINQ to SQL designer and by settings its Delay Loaded value in the property grid:

Note: In addition to configuring the default pre-fetch/delay load semantics on entities, you can also override them via code when you perform LINQ queries on the entity class (I’ll show how to-do this in the next blog post in this series).


Using Stored Procedures

LINQ to SQL allows you to optionally model stored procedures as methods on your DataContext class. For example, assume we’ve defined the simple SPROC below to retrieve product information based on a categoryID:

I can use the server explorer within Visual Studio to drag/drop the SPROC onto the LINQ to SQL designer surface in order to add a strongly-typed method that will invoke the SPROC. If I drop the SPROC on top of the “Product” entity in the designer, the LINQ to SQL designer will declare the SPROC to return an IEnumerable result:

I can then use either LINQ Query Syntax (which will generate an adhoc SQL query) or alternatively invoke the SPROC method added above to retrieve product entities from the database:

Using SPROCs to Update/Delete/Insert Data

By default LINQ to SQL will automatically create the appropriate SQL expressions for you when you insert/update/delete entities. For example, if you wrote the LINQ to SQL code below to update some values on a “Product” entity instance:

By default LINQ to SQL would create and execute the appropriate “UPDATE” statement for you when you submitted the changes (I’ll cover this more in a later blog post on updates).

You can also optionally define and use custom INSERT, UPDATE, DELETE sprocs instead. To configure these, just click on an entity class in the LINQ to SQL designer and within its property-grid click the “…” button on the Delete/Insert/Update values, and pick a particular SPROC you’ve defined instead:

What is nice about changing the above setting is that it is done purely at the mapping layer of LINQ to SQL - which means the update code I showed earlier continues to work with no modifications required. This avoids developers using a LINQ to SQL data model from having to change code even if they later decide to put in a custom SPROC optimization later.


Summary

LINQ to SQL provides a nice, clean way to model the data layer of your application. Once you’ve defined your data model you can easily and efficiently perform queries, inserts, updates and deletes against it.

Using the built-in LINQ to SQL designer within Visual Studio and Visual Web Developer Express you can create and manage your data models for LINQ to SQL extremely fast. The LINQ to SQL designer also provides a lot of flexibility that enables you to customize the default behavior and override/extend the system to meet your specific needs.

In upcoming posts I’ll be using the data model we created above to drill into querying, inserts, updates and deletes further. In the update, insert and delete posts I’ll also discuss how to add custom business/data validation logic to the entities we designed above to perform additional validation logic.

Mike Taulty also has a number of great LINQ to SQL videos that I recommend checking out here. These provide a great way to learn by watching someone walkthrough using LINQ to SQL in action.

read original