Wednesday, January 09, 2008

LINQ and Entity Framework Posts for 1/7/2008+

Note: This post is updated daily or more often, depending on availability of articles. As of this issue, the publication date will be reset after adding significant new posts.

Update 1/9/2008: Date (year) errors fixed.

The VB Team: Writing UNION, TOP and Subqueries in LINQ

The Converting SQL to LINQ, Part 7: UNION, TOP, Subqueries (Bill Horst) post of January 8, 2008 covers use of LINQ Union, Intersect, Except, Take, TakeWhile, and Skip Standard Query Operators in VB 9.0 query expressions.

Added: January 9, 2008

Marcello Lopez Ruiz Clarifies ADO.NET Data Services' URI Format

Marcello's Updates to URL syntax for December CTP of ADO.NET Data Services post of January 8, 2008 advises that the current Astoria CTP uses only the compact URI syntax. Compact URI syntax uses the resource set name followed by one or more comma-separated, single-quoted identifiers enclosed in parenthesis as in: /Customers('ALFKI').

The long-form syntax, described in Mike Flasko and Pablo Castro's URI Format - Part 1 - Addressing resources using URI path segments post of September 21, 2007 in the Astoria Project Team blog, was not implemented, presumably because the team abandoned the Web3S wire format in favor of JSON, ATOM (and hopefully POX) formats only.

Added: January 9, 2008

Julie Lerman: SQL Server CE Provider Coming for Entity Framework December CPM

Julie's SQL Server CE compatibility with EF Beta 3 in a few weeks... post of January 8 quotes the EF team's Jaroslaw Kowalski with the timetable for an upgraded SSCE Entity Framework data provider.

Added: January 8, 2008

Dare Obasanjo Compares LINQ with Python for List Processing

Dare writes a very terse C# LINQ to Objects query to find and display anagrams within 1,219 of the most popular male names in the U.S. in 97 milliseconds or less. Doing the same for 4,275 female names takes about 557 ms.

Added: January 8, 2008

Scott Guthrie Starts Dynamic LINQ Query Series

Scott kicks off his new Dynamic LINQ series with Dynamic LINQ (Part 1: Using the LINQ Dynamic Query Library) post of January 7, 2008 (earlier than usual—11:03 PM) that makes use of the unpublicized LINQ Dynamic Query Library that's included in the C# and VB samples packages you can download from here (C#) or here (VB). Downloads require agreement to the new Microsoft Public License (Ms-PL).

Some bloggers refer to LINQ queries in which you substitute string or numerica variables for literal constants in the query expression as "dynamic." However, the LINQ Dynamic Query Library goes a big step further by letting you substitute composable strings for Standard Query Operator arguments in queries that use method call syntax. The library generates expression trees by parsing the strings. Of course, You exchange type safety and IntelliSense for flexibility when you employ this technique.

Scott offers VB and C# ASP.NET Web site samples, and points to the Albahari brothers' Dynamically Composing Expression Predicates post that describes their PredicateBuilder class. PredicateBuilder is part of their LINQKit productivivity kit for LINQ to SQL, which every LINQ partisan should have.

Update: In response to a comment, Scott adds the following advice:

LINQ to SQL uses type-safe data model classes, you are protected from SQL Injection attacks by default.  LINQ to SQL will automatically encode the values based on the underlying data type.

BTW - you can use the Where() extension method either like so:

   .Where(String.Format("CategoryID={0}" & Request.QueryString["id"])


   .Where(String.Format("CategoryID=@0", Request.QueryString["id"])

The second option allows you to specify any parameter markers you want in the query, and then in[j]ect the values as params that you pass separately.

Be sure to read the comments and Scott's replies.

Added: January 8, 2008

Stefan Cruysberghs Examines Dynamic LINQ Where and OrderBy Clauses

Apropos Scott's Dynamic LINQ queries post, Belgian developer Stefan Cruysberghs' .NET - LINQ to SQL - part 4 article of January 7, 2008 goes into the details of

  • Anonymous functions and IEnumerable
  • Lambda expression trees and IQueryable
  • PredicateBuilder class and combining expressions
  • Predicate library

for creating dynamic Where and OrderBy clauses.

The article also includes links to his three preceding LINQ-related Web pages. Click here for a complete list of Stefan's articles in English.

Update 1/9/2008: Stefan's recent articles cover a wide range of topics of interest to VS developers, including detailed data on the performance improvement you can expect from PLINQ. His English .NET RSS feed includes brief abstracts.

Added: January 8, 2008

LINQ to XML: Grouping and Aggregation Gotchas, Part I

LINQ to XML is a candidate to replace XQuery for grouping elements, transforming Infosets and aggregating numerical data. It also can supplant XPath for navigation and XSLT for grouping and transformation. Aggregating elements or element groups and generating sum, average, minimium and maximum values is one of the most common uses for XQuery, XPath and XSLT.

However, non-trivial LINQ to XML examples that demonstrate element grouping and numerical aggregation are few and far between. This LINQ to XML: Grouping and Aggregation Gotchas, Part I post of January 7, 2008 describes two Microsoft grouping samples that don't behave as expected.

C# Team Posts Custom LINQ to TerraServer Implemetation

Charlie Calvert's TerraServer Sample: A LINQ Provider post of January 6,2008 announces the arrival of yet another custom (not third-party in this case) LINQ implementation: LINQ to Terra Server.

Here's the project's description from the project's ReadMe.htm file:

This sample is a custom LINQ provider for the TerraServer-USA Web service. It also contains a sample client application that uses the custom LINQ provider to query the Web service for geographical data.

The TerraServer-USA Web service exposes a method that returns information about locations in the United States when the method is given part or all of a location name. This method, which is named GetPlaceList, is the method that the LINQ provider calls to obtain the data that the LINQ query is run against. The provider uses Windows Communication Foundation (WCF) to communicate with the Web service. For more information about the TerraServer-USA Web service, see Overview of the TerraServer-USA Web Services.

A LINQ provider that implements the System.Linq.IQueryable<T> interface, such as this one, enables LINQ queries to be written against the data source that the provider connects to. A provider may execute the query functionality on the data itself, or it may translate the LINQ query into a query language that is appropriate for the data source that it connects to. This provider obtains raw data from the Web service and then modifies the original query in such a way that LINQ to Objects handles the query execution.

And here's sample output from the console:

States that have a place named "Redmond":
West Virginia

Number of places whose names start with "Lond": 29

Places, ordered by state, whose name is either "Johannesburg", "Yachats", or "Seattle":
{ Name = Johannesburg, State = California }
{ Name = Johannesburg, State = Michigan }
{ Name = Yachats, State = Oregon }
{ Name = Seattle, State = Washington }
{ Name = Johannesburg, State = Wisconsin }

MSDN's new Walkthrough: Creating an IQueryable LINQ Provider article shows you how to create the provider and client from scratch. (The link in the ReadMe.htm is incorrect.)

The LINQ to TerraServer code is part of a set of C# samples that you can download from here (requires agreement to the new Microsoft Public License (Ms-PL). 

Note: A few years ago, I wrote a graphic Web service front end to TerraServer in VB 2003. "Build Real-Time Web Images" article in the August 2004 issue of Visual Studio Magazine described a Visual Basic .NET 2003 graphic consumer of Web Services, as well as Microsoft MapPoint services. You can download the source code for the project here.

David Hayden Continues His Dynamic Data Series with Metadata Providers Tutorial

David says in ASP.NET Dynamic Data Tutorial - BuddyMetadataProvider and Custom Metadata Providers of January 6, 2008:

This is my 5th tutorial on the new ASP.NET Dynamic Data that ships with the ASP.NET 3.5 Extensions CTP. ASP.NET Dynamic Data is an alternative to code generation in helping one build database-driven web applications in a more productive manner. ...

If you don't like adding metadata to partial classes via attributes, the MVCToolkit contains a couple of custom metadata providers that you can use as a vehicle for adding metadata to your Dynamic Data Applications in different ways:

  • BuddyMetadataProvider
  • XmlMetadataProvider

And goes on to explain how to use both.

Ruurd Boeke Demonstrates Entity Framework's Table Per Type Inheritance

Catch-up: Ruurd's How To: Table per type inheritance with Entity Framework post of January 2, 2008 provides an illustrated walkthrough for implementing TPT inheritance with the classic three tables and classes: Person and related/derived Employee, and Customer entities.

Update January 9, 2008: Following are links to some of Ruurd's earlier Entity Framework posts:

Update January 10, 2008: Fixed error in spelling of Ruurd. Sorry about that.

Scott Hanselman Endorses LINQ to Mock (Moq)

From the "How Did I Miss This?" department: Scott's Moq: Linq, Lambdas and Predicates applied to Mock Objects of December 19, 2007 starts with:

Kzu and friends have a new pet project called Moq, which may be the coolest derivative open source project name ever.

And ends with:

Slick. Moq is definitely a project to watch.

In between, Scott compares NMock, RhinoMock, TypeMock and Moq (a.k.a., LINQ to Mock for provider naming consistency.)

The "Daniel Cazzulino and Juan Wajnerman Create LINQ to Mock (Objects)" topic of LINQ and Entity Framework Posts for 12/17/2007+ has more details on the release of LINQ to Mock.