Sunday, May 11, 2008

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

Note: This post is updated daily or more frequently, depending on the availability of new articles.

Dinesh Kulkarni: Removing an Item from a LINQ to SQL Collection Doesn't Delete It

Dinesh observes in his LINQ to SQL Tips 4: Use DeleteOnNull if you want to delete object with null FK post of May 11 that:

If I remove one of the O[r]derDetails from Order.OrderDetails collection, I see that the reference OrderDetail.Order is set to null but this just orphans the OrderDetail; it is not deleted. How can I change that?

Dinesh provides a pair of alternative changes to the generated code to infer an invocation of the DataContext.DeleteOnSumbit() method.

Added: May 11, 2008

Ilan Assayag Finds LINQ's ElementAt Method is Slow

In his Linq: Composite keys don't work + Beware of ElementAt ... post of May 11, 2008, Ilan can't use one of Shital Shah's four approaches for LINQ to Object joins on composite keys to join a LINQ to SQL result and an in-memory List<T> of the same length. So he tried using the ElementAt() Standard Query Operator and found it took "AGES to complete. The solution was to turn the inputs into arrays and process them.

Added: May 11, 2008

EntitySpaces to Support LINQ to SQL Libraries in Next Release

EntitySpaces is a commercial O/RM tool that competes with LINQ to SQL and Entity Framework. The Entity Spaces blog's May 11, 2008 announcement, EntitySpaces 2008 - LINQ to SQL in Next Beta, states that the product's generated classes will include classes from System.Data.Linq and System.Data.Linq.Mapping if you mark the LINQ to SQL Support check box of the Advanced page of the configuration dialog.

Applications that take advantage of this option are limited to the SqlClient provider and SQL Server as the data store. EntitySpaces has its own providers for Microsoft Access, Oracle, MySQL, VistaDB and PostgreSQL.

The EntitySpaces 2008 - LINQ to SQL in Next Beta (Part 2) post of the same date says that you can use LINQ to SQL to populate data into an EntitySpaces collection directly.

Added: May 11, 2008

Beth Massey Demonstrates Finding XML Nodes and Changing their Value with LINQ to XML

Her Quickly Changing Values of XML Elements Using LINQ post of May 9, 2008 shows a simple LINQ to XML query to find a particular node and then change the value of two of its members within a For Each loop.

Applying the SingleOrDefault() Standard Query Operator would be a better alternative if you want to make sure that only one node is updated (see the next post).

Added: May 11, 2008

Jimmy Bogard: Minimize foreach Loops and Temporary Lists with LINQ Query Operators

Jimmy suggests transformations, aggregations, concatenations, and filtering operations as candidates for simplification with LINQ in his LINQ query operators: lose that foreach already! post of May 9, 2008.

Added: May 11, 2008

Darrell Mozingo Proposes Using Data Transfer Objects with LINQ to SQL

His Loading a DTO from LINQ To SQL post of May 9, 2008 starts by defining the the Data Transfer Object (DTO) pattern:

A Data Transfer Object (DTO) is a plain old CLR object (POCO) mainly used to pass data between tiers and remote calls. They’re basically classes with getters, setters, and perhaps a constructor or two, but no methods. They’re dumb objects that simply hold data.

He then goes on to explain the benefits of a DTO as an intermediary between LINQ to SQL objects and other application layers or tiers and then shows the LINQ code to create a DTO for a PersonDTO object with a GetPerson() method. The Business layer then invokes the PersonDTO.GetPerson(personID) method and executes similar code in the business layer.

PersonDTO looks to me to be a DTO with a method and it's definitely read-only.

Martin Fowler recommends considering DTOs only for passing data to remote tiers. He quotes contributing author Randy Stafford:

Don't underestimate the cost of [using DTOs].... It's significant, and it's painful - perhaps second only to the cost and pain of object-relational mapping.

Added: May 11, 2008

Matt Hunter Releases RC1 of LINQ to Entity Base

LINQ to Entity Base is a base class that provides change tracking while disconnected from the entity context and supports WCF. Matt's Version 1.0 Release Candidate 1 of LINQ to SQL Entity Base released!!! post of May 9, 2008 incorporates the following changes;

  • Added two static helper methods for serialization/de-serialization of entities.
  • Now automatically returns KnownTypes if Entity Base class is in the same assembly as your Entity classes.
  • You can now set the initial state of the root entity (e.g. New or Deleted)
  • Demo is now in the form of a Client/Server architecture, with WCF used for communication.
  • Added "LINQEntityState" property which returns an enum indicating the state of the entity.

You can download LINQ to Entity Base RC1 from CodePlex.

Added: May 9, 2008

Mark Blomsma Builds a Simple RSS Aggregator with LINQ to Objects and WCF

Most RSS/Atom aggregators use LINQ to XML, but Mark's Building a RSS aggregator using LINQ to Objects and WCF 3.5 post of May 9, 2008 takes advantage of WCF's SyndicationFeed.Load() and SyndicationFeed(items) methods to take the prize for code brevity.

Added: May 9, 2008

Julie Lerman Explains the "Platinum Rule" for Attaching an Object Graph

Julie explains that "an object graph (for example when a customer is attached to an order which is attached to some line items) must be completely in or completely outside of the ObjectContext" in her Entity Framework's Golden Rule and its Platinum Rule post of May 8, 2008.

She attached an Order instance to a Customer instance, attached the Customer (but not the Order) to an ObjectContext for change tracking, and found that the Order were attached and being change tracked because the association created an object graph. But if you detach the Customer, the Order (and its LineItems, if present) remain attached.

Julie's Advanced Entity Framework: Take Charge of Object Services session for Tech*Ed North America Developers 2008 conference:

"... drills into how the ObjectContext manages relationships and how you can control its behavior. This is especially important in SOA scenarios where you may need to transport ObjectGraphs. We also look closely at change tracking, focusing on the challenges and solutions for dealing with data concurrency when moving objects across tiers in your enterprise applications.

She's also presenting Microsoft .NET Framework 3.5 Data Access Guidance.

Added: May 9, 2008

Jim Wooley Investigates Using Unmapped Properties in a Mapped Class in a LINQ to SQL Projection

In his Projecting into an unmapped property from a LINQ to SQL query post of May 8, 2008, Jim says:

On page 216 of LINQ in Action, I made a comment that unmapped properties in a mapped class cannot be used in a LINQ to SQL projection. This was true with the beta bits, but only partially true with the release bits.

However, he concludes:

So the question that came up asks if the next printing of the book needs to be adjusted to remove the statement that you can't project an unmapped property. While you can indeed project these properties, you can't use them elsewhere in the query. ... Because of this, I plan to leave the note in the chapter warning you of using the unmapped property in your query.

Added: May 9, 2008

PHP/Rails/MySQL Developer Finds ASP.NET and LINQ to SQL Fast, Cost- Effective and Reliable

Howard Baines, a UK Web design and development agency, says in a Building a web app the Microsoft way post of May 8, 2008:

We’ve worked with PHP, Rails, MySQL and others, and have experienced the highs and lows of doing so. Late last year we decided to fly in the face of popular opinion and build a web app of our own… using the Microsoft platform. ...

We decided to build a meeting organizer application which we called ‘Meet with Approval’. The application allows anyone who wants to arrange a meeting to create a dedicated event page with date and time options and send out email invites. ...

The real bonus came in the form of the InteliSense in Visual Studio which not only made learning and writing LINQ [to SQL] queries fast but also supported our underlying data model. InteliSense within Visual Studio included support for frontend JavaScript which again helped to speed up development. Moreover the InteliSense features really cut down on the number of time wasting runtime errors and helped to reduce bugs. In fact using the various prebuilt controls and functions of .NET helped us to significantly cut down the number of bugs. ..

Within three weeks we were able design, develop and deploy our application at extremely low cost. Since launching in late 2007 we have had only 2 bugs reported with over 2000 users in the system and over 500 meetings created. We felt that we were able to deliver on our objectives of fast, cost effective, reliable development that produced a great user experience which you can judge for yourselves at

Their case study is on the Microsoft website as part of the Heroes Happen Here Launch Evidence: Howard Baines: Start-Up Migrates from Open Source and Develops Web Solution in Just Three Weeks.

Added: May 9, 2008

Matt Hidinger Adds Audit Updates Feature to  LINQ to SQL

In his LINQ to SQL Audit Trail post of May 8, 2008, Matt explains his approach to adding an audit trail to a LINQ to SQL application:

Natu[r]ally, there are many ways to tackle this [auditing] problem. In the past I have either relied on writing database Triggers for the tables, or wrote the Auditing logic right into the stored procedure that was doing the modification. But this time, since the project is utilizing LINQ to SQL, I had a more ambitious idea in mind.

The Goal

Create a flexible, and automated Auditing solution that would allow my team to add Audit tracking to any table in our database, with only a single line of C# code.

The sample code, which audits changes to Northwind Products and Categories table, and an ASP.NET demo project is available for download here.

Added: May 9, 2008

LINQ, Entity Framework, ADO.NET Data Services, SQL Server Data Services, Data Synchronization, and SQL Server Compact at Tech*Ed

The following two posts of May 8, 2008 list and describe the sessions at Tech*Ed 2008 North America Developers, June 3-6, 2008, in the Orange County Convention Center, North/South Building, Orlando, Florida, that a related to this blog's primary topics:

The preceding lists were compiled from the Tech*Ed Developers 2008 Session Catalog.

Added: May 8, 2008 16:00 PST Updated: May 9, 2008

Eugenio Pace Explains How to Enable LitwareHR's Offline Proxy

In his You don't have a beta account with SSDS, but you'd like to use the latest LitwareHR anyway post of May 8, 2008, Eugenio explains that the LitwareHR front-end for SQL Server Data Services also has a proxy to enable off-line development and shows you how to enable it if you don't have an SSDS beta account.

Added: May 8, 2008 16:00 PST

Doug Rothaus Continues his Visual Basic XML Odyssey

Doug's VB XML Cookbook, Recipe 4: Get Inner XML from the Nodes Property (Doug Rothaus) post of May 8, 2008 discusses the differences between System.Xml's InnerText and InnerXML properties:

If you’re familiar with the classes in the System.Xml namespace, you will immediately recognize this behavior. The solution is to embed the inner XML of the element rather than the inner text (the Value property). While the System.Xml classes expose both InnerText and InnerXml properties, LINQ to XML does not. Inner text is returned from the Value property, and inner XML is returned from the Nodes property. Why the difference? The InnerXml property returns a string of XML, which would have to be re-parsed into XML objects. The Nodes property returns a collection of LINQ to XML objects, which you can manipulate or embed as a whole into XML Literals making the Nodes property a powerful tool for transforming XML.

Added: May 8, 2008 16:00 PST

Justin Etheredge Explains the Workings of LINQ's SelectMany Operator

In his The Linq SelectMany Operator post of May 8, 2008, Justin describes how the less commonly used SelectMany Standard Query Operator flattens sequences to avoid nested results.

Added: May 8, 2008 16:00 PST

Randolph Cabral Explores Creating Business Entities from Data Entities

Randolph's Exploring N-Tier Architecture with LINQ to SQL (Part 3 of n) episode of May 8, 2008 explores object composition as practiced by the Gang of Four (GoF) by creating "a business entity layer that abstracts the data entities away and gives us a nice place to add domain logic."

Added: May 8, 2008 16:00 PST

Download Northwind.sdf with Column and Constraint Name Fixes

The version of Northwind.sdf for SQL Server Compact Edition (SSCE) v3.5 installed in the \Program Files\Microsoft SQL Server Compact Edition\v3.5\Samples folder by Visual Studio 2008 has spaces in column and foreign-key constraint names. My uploaded version corrects this defect so Entity Framework and LINQ to SQL sample projects can use the same queries.

The details are in Upgraded Northwind.sdf File for SSCE v3.5 Available for Download of May 8, 2008.

Steve Godbold Analyzes the Number of Connections for LINQ to SQL Queries

In his LINQ to SQL and Connections post of May 8, 2008, Steve counts three openings and closings of the connection to a test database for a query that returns a sequence of 100 entities and another query that adds a row to the table.

No surprises here.

Jimmy Bogard Replaces Filter, Map, and Reduce Functions with LINQ Where, Select and Aggregate

Jimmy shows how to replace function programming's "big three higher-order functions," Filter, Map, and Reduce with LINQ's Where(), Select() and Aggregate() Standard Query Operators (SQOs) in his Enhancing mappers with LINQ post of May 8, 2008.

Note: Map and Reduce are, as you'd expect, the functions behind Google's and other's MapReduce frameworks.

Rob Conery Closes in on the MVC Storefront with Data Updates from the Shopping Cart

Rob says in his MVC Storefront, Part 9: The Shopping Cart post of May 8, 2008:

In this episode I dive into implementing the Shopping Cart in a basic way so I can run a spike to make sure my pattern can push data nicely back into the DB without problems.

He also provides brief descriptions of and links to the previous eight episodes.

Bill Horst Continues His Converting SQL to LINQ in Visual Basic Series

Part 10 is Converting SQL to LINQ, Part 10: Like (Bill Horst) of May 7, 2008. The Like operator is a keyword in VB.

The LINQ version is identical to the keyword's, but the SQL Server LIKE operator doesn't support all VB options, such as # to match any single digit.

Julie Lerman Discusses the Need of Delete Stored Procedures for Foreign Key Parameters

The Entity Framework is very picky about the use of stored procedures for create, update, and delete (CUD) operations. Julie outlines these requirements in her Delete Stored Procs and Navigations in the Entity Data Model post of May 7, 2008 with emphasis on the need to include foreign-key parameters for associations in DELETE stored procedures.

Ryan Dunn Emphasizes Reducing Capital and Operating Expenditures with SQL Server Data Services

In The Business Value of SQL Server Data Services of May 7, 2008, Ryan says:

One of the greatest business values (as opposed to technical values) you get from SSDS (and cloud services in general) is the ability to redeploy the capital to other resources.  In the case of CapEx, you can deploy this perhaps to marketing or content creation.  In the case of OpEx, those expenses can be redeployed to more useful tasks in the enterprise (creating new systems, upgrading, and expanding operations perhaps?).

I think SQL Server Data Services will need several rounds of feature additions before it's ready to replace most on-premises SQL Server 2005+ installations.

FarPoint Adds LINQ Support to its Spread[sheet] Control for Windows and Web Forms

In a brief FarPoint Spread and LINQ post of May 7, 2008, the FarPoint blog says:

Spread for Windows Forms supports LINQ data sources and can operate in applications that make use of LINQ extensions. You can use LINQ in application development to do queries, use the built-in type checking and IntelliSense it affords, and with Spread for Windows Forms, bind to results retrieved from a LINQ query.

As for Spread for ASP.NET, the .NET framework provides a LinqDataSource control. And, it can be set as the DataSource for Spread for ASP.NET.

Pablo Castro Comments on Entity Framework's Database Independence

His Provider availability enables Entity Framework and Data Services over many database vendors post of May 7, 2008 says, inter alia:

I've been looking at all the buzz about adoption of the ADO.NET Entity Framework provider model and how it enables access to many databases. This is a big deal... we kind of slowed down on database independence with previous versions of ADO.NET. This new round restores the database independent capabilities.

Matt Warren mentions the opposite approach taken for LINQ to SQL in his Mocks Nix - An Extensible LINQ to SQL DataContext post of May 4, 2008:

LINQ to SQL was actually designed to be host to more types of back-ends than just SQL server. It had a provider model targeted for RTM, but was disabled before the release. Don’t ask me why. Be satisfied to know that is was not a technical reason. Internally, it still behaves that way.

Obviously, it was a marketing reason. I'm glad the EF folks took a different approach.

John Papa Promises a Silverlight 2.0 Demo with LINQ to SQL and WCF

John's been concentrating on Entity Framework for quite a while, but says in his Silverlight, WCF and LINQ to SQL post of May 7, 2008:

I've had some requests lately to write some articles that work with LINQ to SQL. I've ben focusing on the Entity Framework a lot due to its vast nature and that fact that its still relatively unknown to many people. So I am going to work on a LINQ to SQL project that ties into a multi tier model. I am also going to show how this can be hooked into a  Silverlight 2 UI that connects through WCF to the lower layers.

David Sceppa Refreshes the Entity Framework's Third-Party Data Providers List for Beta 3

Dave's Recent ADO.NET Entity Framework provider news - Demos and downloads post of May 6 lists the status of third-party data providers that support Entity Framework Beta 3:

  • Core Lab (Oracle, MySQL, PostgreSQL and SQLite)
  • IBM (DB2, IDS and U2)
  • MySQL (MySQL)
  • Npgsql (PostgreSQL)

Oracle and DataDirect are conspicuous by their absence.

Avi Wortzell Shows You How to Add ADO.NET 2.0's SqlBulkCopy Feature to LINQ to SQL

In Implementing SqlBulkCopy in Linq to Sql of May 6, 2008, Avi shows you how to write a LinqBulkCopyReader as a generic class which inherits from the SqlBulkCopyReader class that lets you do bulk inserts with LINQ to SQL.

Roy Osherowe Implements LINQ to Regex

Roy takes Josh Flanagan's Readable Fluent Regex Api and wraps it with LINQ in his Introducing LINQ To Regex post of May 6, 2008. Fluent Regex syntax, which Josh designed for readability, resembles LINQ's composable method syntax, which simplified the process. The source code and binaries are available here.

Very handy, especially if you're not a Regex guru.