Search results for Posts relating to LINQ - ThinqLinq by ThinqLinq


ThinqLinq Samples on Github

When I first created this site, I used it both as a test bed for technologies as I played with them and as a repository for others to use for my presentations and other insights. Over the years people have been free to grab these samples, but haven’t had good ways of giving back to help improve the samples. In the mean time, there have been quite a number of technology changes. While I may have been late to the party on some, there’s only so many things one can focus on. One of the advances we’

Left Outer Joins in LINQ with Entity Framework

As I spend more time reviewing code with clients and on public forums, I’m constantly seeing cases where people have issues with Outer joins in LINQ and the various flavors of LINQ. In this post, I’m going to look at a couple options from a syntax perspective that you can use to make working with outer joins easier with LINQ. Naturally, we have a much deeper discussion of outer joins in our book that you’re welcome to dig into as well. Typically, if you do a join in LINQ, it will perform an inne

Multi Lingual LINQ and Rx

“Imitation is the sincerest [form] of flattery” – Charles Caleb Colton When dealing with technology, or nearly any other creative endeavor, one of the ways that you know if you’ve discovered a successful creation is to see how much it is embraced by not only your peers, but also your competitors. We can see this in quotes by Shakespeare, the music of Bach, parodies of Peter Schickle, Hip Hop sampling, and countless others. This blog is based on one of the more significant technologies that many

Hierarchical Trees from Flat Tables using LINQ

I’m often tasked with creating a tree representation of a structure from a flat self-referencing table. For example, in the EF extensions to Northwind, they extended the Employee table so that it has a self-referencing “ReportsTo” column. As you can see from the data below, Andrew Fuller does not report to any other employees, but Nancy, Janet, Margaret, Steven, and Laura all report to Andrew (because their ReportsTo value is the same as Andrew’s EmployeeID). Likewise Michael, Robert, and Anne a

Aggregate clause issues

I was reviewing a Stack Exchange message regarding the Aggregate clause in VB () where they found that the query was issuing multiple requests to the database and occasionally returning the entire database table to memory and using LINQ to Objects over the result. I also found that Frans Bouma blogged about this back in 2008 at  . Consider the following LINQ query over Northwind: Dim query = Aggregate o in Orders             &#1

LINQ to Database Performance hints

Although I’ve been writing primarily about RX here for a while, I still dig into some good old LINQ to SQL / EF quite a bit. Along the way, I’m frequently finding more tidbits to throw in the toolbox and thought I’d share some observations from a recent performance tuning project. (I’ll avoid disclosing the client and will change the database model to Northwind for this discussion protect the guilty.) In this project, I was brought in at the end of the project as things started going south to

Ix Interactive Extensions return

If you’ve been following the Reactive Extensions for any time, you may have seen that the team utilized the duality between IEnumerable and IObservable to not only create parallel extension methods of the enumerable versions on IObservable, but they also created IEnumerable versions of the additional methods that they added to IObservable as well. This formerly was in the Interactive libraries that came as part of the Rx bits. When the version 1 release of Rx came out however, these IEnumerable

Does LINQ to SQL eliminate the possibility of SQL Injection

By default, LINQ to SQL uses parameterized queries rather than concatenated strings when executing your LINQ queries. As a result, if a user tries to perform SQL Injection by improperly escaping parts of the SQL, the escape is considered part of the parameter rather than part of the query and thus avoids the injection. However, as we discussed in chapter 8 of LINQ in Action, LINQ to SQL greatly reduces the possibility of SQL Injection, but doesn't completely eliminate it. For example, if you a

LINQ in Action in Chinese

Today, I received an unexpected surprise in the mail. A copy of LINQ in Action translated into Chinese. We were aware that someone was making a Chinese translation, but only expected it to be a couple chapters. It turns out the entire book, including the bonus chapter 14 (LINQ to Datasets) which didn't make the printed English version of the book. Hopefully nothing got lost in translation for this version. If you read Chinese, check the book out and let us know what you Thinq.

Replace Foreach with LINQ

One of the best ways to start Thinqing in LINQ is to find places where you can replace iterative loops with LINQ queries. This won’t necessarily make your applications any faster at the moment, but by taking advantage of the declarative syntax, it will allow you to change your underlying implementation (ie. parallelize it with PLINQ) easier in the future. Recently, I came across some code that mimicked creating a control array as we used to have in VB6 by iterating over a list of fields and addi

LINQ to CSV using DynamicObject and TextFieldParser

In the first post of this series, we parsed our CSV file by simply splitting each line on a comma. While this works for simple files, it becomes problematic when consuming CSV files where individual fields also contains commas. Consider the following sample input: CustomerID,COMPANYNAME,Contact Name,CONTACT_TITLE ALFKI,Alfreds Futterkiste,Maria Anders,"Sales Representative" ANATR,Ana Trujillo Emparedados y helados,Ana Trujillo,"Owner, Operator" ANTON,Antonio Moreno Taquer

LINQ to CSV using DynamicObject Part 2

In the last post, I showed how to use DynamicObject to make consuming CSV files easier. In that example, we showed how we can access CSV columns using the standard dot (.) notation that we use on other objects. Using DynamicObject, we can refer to item.CompanyName and item.Contact_Name rather than item(0) and item(1). While I’m happy about the new syntax, I’m not content with replacing spaces with underscores as that doesn’t agree with the coding guidelines of using Pascal casing for properties

LINQ to CSV using DynamicObject

When we wrote LINQ in Action we included a sample of how to simply query against a CSV file using the following LINQ query: From line In File.ReadAllLines(“books.csv”) Where Not Line.StartsWith(“#”) Let parts = line.Split(“,”c) Select Isbn = parts(0), Title = parts(1), Publisher = parts(3) While this code does make dealing with CSV easier, it would be nicer if we could refer to our columns as if they were properties where the property name came from the header row in the CSV file,

LINQ tools on the Toolshed

This summer at the Jacksonville Code Camp, I had the pleasure of being part of the taping of Russ' Fustino’s Toolshed. Finally, the episode has  been posted on Channel9 for you to enjoy. Here’s the overview of the episode. Toolshed: Episode 5 - Its All About The Tools TV Show Episode 5 has killer content on Deep Zoom, Expression Web 3, a codeplex project on a Snippet Editor for Visual Studio, LINQ Tool Samples, LINQ Pad, Link To Twitter, Expression Blend 3 Importing Adobe assets, and an

Setting DataContext Connection String in Data Tier

LINQ to SQL offers a quick mechanism to build a data tier in a n-Tier application. There’s a challenge when using the DBML designer in a Class Library. The designer stores the connection string in the Settings file. Although it appears that you can change it in the config file, any changes you make there will be ignored because they are actually retained in the generated Settings file. While you could go into the DataContext’s .Designer file and change the location of the connection string, an

Using Cast Or OfType Methods

When working with generic lists, often you want to work with a more specific type than the list natively exposes. Consider the following where Lions, Tigers and Bears derive from Circus Animal: Dim items As New List(Of Object) items.Add(New Lion) items.Add(New Tiger) items.Add(New Bear) Dim res1 = items.Cast(Of CircusAnimal)() Dim res2 = items.OfType(Of CircusAnimal)() In this case, both res1 and res2 will return an enumerable of CircusAnimal objects rather than jus

Watch language differences when parsing Expression Trees

I’ve run into a number of cases where people have built LINQ providers and only tested them with C# clients. In one case, I was sitting next to the person who wrote the provider when we discovered that using a VB client didn’t work with their provider because they failed to test it. I’ve even seen it in the sample Entity Framework provider  available on the MSDN Code Gallery when parsing the .Include() method. Hopefully, you will be able to access my VB translation of the EF sample provid

Testing to see if a record Exists in LINQ to SQL

There are a number of options you can consider when testing to see if a record exists using LINQ to SQL. Which one should you use? It depends… In general, check the generated SQL for various options in SQL Management Studio to see the how the various execution plans compare. For example, each of the following can tell you if a record exists. Dim q1 = Customers.FirstOrDefault(Function(c) c.City="London") Dim q2 = Customers.Count(Function(c) c.City="London") Dim q3

Euler Primes with LINQ Iterators

Thanks' to Steve Smith’s Project Euler with LINQ, I’ve recently begun playing with the Project Euler questions seeing how far I can push my algorithm skills along with LINQ and LINQPad. LINQPad makes it easy to slap together some code samples and output results, including performance metrics, so I don’t need to worry with that plumbing code and can focus on creating fast code. While working on one of the problems I realized the solution would offer a good opportunity to demonstrate a nuance of

LINQ Tools

I’ve recently started giving a series of talks on LINQ based tools. While Visual  Studio offers a lot in regards to support for LINQ, there are a number of mostly free tools that come in handy both from a usability and a learning experience. I gave a brief look at some of the tools as part of Russ’s Tool Shed which should be airing on MSDN’s Channel 9 in early October. In addition, I’m premiering the full presentation at this weekend’s Tallahassee Code Camp. If you can’t make it out, feel f

Generating Interfaces for LINQ to SQL Entities

At DevLink I had the pleasure of presenting a session on LINQ to SQL Tricks and Tips. The slides and demos for LINQ to SQL Tricks and Tips are available on my download page if you are interested. Following the session, an attendee voiced the desire for LINQ to SQL to create interfaces while it creates the class definitions in order to make it easier to mock the entities in unit testing scenarios. As part of the presentation, I showed Damien Guard’s L2ST4 code generation template. The great thin

Site updated with MVC

In case you haven't been following along the recent posts, I've been exploring ASP.Net MVC recently using this site as a guinea pig. Today I deployed the updated bits and hope you find them to be an improvement on the older site. I've tried hard to keep backwards compatibility with the old site links via some tricks in the Routing engine. Please take a look around and let me know if you find any links that aren't quite working correctly. Please be patient as it may be a bit before all of the leg

Adding Property Get logging to LINQ to SQL with T4

After my last INETA talk in Sarasota, I had two separate people ask me how to enable auditing of LINQ to SQL when properties are read. Currently the classes created by the LINQ to SQL designer and SqlMetal add events to track before and after an individual property are changed through the INotifyPropertyChanged and INotifyPropertyChanging interfaces, but they don't include hooks to detect when a property is read. One option to add read notification is to replace the default code generator with

LINQ to SQL DataLoadOptions.LoadWith and Take

While trying to increase the performance of this site, I found a bug which may drastically slow the performance. By default when navigating to child objects from a parent object, LINQ to SQL lazy loads the children. This is good when you don't know if you want the children. However, on this site when viewing posts, I ALWAYS display the categories and number of comments. As mentioned in LINQ in Action, you can eager load child records using the context's LoadOptions to set the child to be eagerl

Binding Anonymous Types in MVC Views

While translating this site over to MVC, I ran into a challenge when converting the RSS feed implementation. Currently I'm using XML Literals to generate the RSS and I could certainly continue to use that track from the Controller similar to the Sitemap implementation on Mikesdotnetting. However, putting the XML generation in the controller directly conflicts with the separation of concerns that MVC embraces. If I were only displaying one RSS feed, I might be willing to break this here. However,

LINQ Bootcamp coming to Birmingham, AL

If you are in the Birmingham, AL area on July 25-26, consider signing up for the free two day LINQ Bootcamp event. I'm hoping to be there to help answer your questions as well. If you're interested in more information, here's a copy of the original announcement: …The upcoming LINQ Bootcamp [will be] on July 25th and 26th. To register for this great event please go to . Seating is limited to this free event. We still need volunteers for presenting, current

How do Stored Procs fit with LINQ

At Codestock, David Giard asked me about the pros and cons of using stored procedures or using OR/M tools like LINQ to SQL or Entity Framework. There is no silver bullet in terms of which to use. In many cases you need to use a combination of techniques depending on your particular needs. Watch the video to see what you need to consider when making this decision.

Iterators OR Excuse me waiter theres a goto in my C sharp

At Codestock '09, I gave my LINQ Internals talk and had a number of people express shock when I showed the underlying implementation of their beloved iterators when looking at the code through Reflector. Let's look first at the C# that we wrote. This is similar to the implementation of LINQ to Object's Where method as shown in the sequence.cs file that's part of the C# Samples. public static IEnumerable Where(this QueryableString source, Func predicate) { foreach (char curChar in source)

LINQ Tools coming to Russ Tool Shed

Russ Fustino and Stan Schultes have recently started bringing their popular Russ' Tool Shed show to the internet. If you want to check out the show, head on over to They also have all of the resources, including source code, slides, and demo scripts available at I was there when they recorded the first episode at the South Florida code camp as an attendee. We're hoping to do a recording at one of the upcoming

Fetching XML from SQL Server using LINQ to SQL

With SQL Server, you can use the For Xml clause (read more in BOL). The quickest option is to add For XML Auto at the end of a SQL statement. You can do this with dynamic SQL or inside a stored proc. If you use a stored proc, the DBML tool doesn't recognize this as XML (and return it as an XElement as it does for XML Data type columns). Regardless of whether you are using stored procs or dynamic SQL, the server returns the result as an array of strings broken up into 4000 character chunks. It is

Add Extension Methods in LinqPad

As we already announced, the samples for chapters 1-8 of our LINQ in Action book are available through LINQPad. This includes the LINQ to Objects and LINQ to SQL. I've been working on the LINQ to XML chapters (9-11) and hope that we will add them to the download soon. In the process, I've needed to learn a bit about how LINQPad works under the covers in order to add specialized classes. By default, LINQPad offers three options: Expressions, Statements and Programs. With the Expressions, you can

LINQ In Action Samples available in LINQPad

I've been asked for some time what I think about the LINQPad tool. For those of you unfamiliar with it, LINQPad is a small but powerful tool that allows you to test your LINQ queries along with other VB and C# code. With this tool, you insert your code snippets in the code window and run it directly. If you point it to a database connection, LINQPad will build the .DBML behind the scenes and let you access the generated classes just as you would inside visual studio. When you execute the code, y

LINQ to SQL designer in VS 2010 Beta 1

There is a bug in the upgrade process when converting a LINQ to SQL designer (.dbml) file from VS 2008 to VS 2010. They changed the implementation to hold the layout information in a .dbml.diagram file rather than the .dbml.layout file. Instead of just renaming the existing file, it replaces it with a new one effectively loosing all of the layout customizations you may have made to the design surface. Luckily there is an easy fix. Just delete newly created .diagram file and then rename the old .

LINQ to SQL enhancements for 2010

One question that I'm asked repeatedly is, "Is LINQ dead?" The quick answer is, NO. The more appropriate question is "Is LINQ to SQL dead?" That one is a bit trickier, particularly after some of the blog posts from the data programmability team regarding their emphasis moving forward for LINQ to SQL and the Entity Framework. My take on it is that LINQ to SQL is in a similar situation to Winforms. Both are still supported and have teams dedicated to them, but don't expect much in terms of new fe

LinqDataSource and CUD operations with Inheritance

When I added the Pingbacks and Trackbacks, I changed the implementation of the Comments to use an inheritance model (TPH) where Comments, Trackbacks, and Pingbacks all inherit from the abstract CommentBase class. To refresh your memory, here's the appropriate part of the DBML designer surface: While this works fine with minimal changes when viewing data, it can cause problems if you are using the LinqDataSource for editing values. When trying to update or delete a record, you may encounter a me

Implementing Pingbacks

Recently, I discussed Sending and Receiving TrackBacks on this blog. The TrackBack API is not the only mechanism which blog engines use to communicate between each other about the links that are included in individual posts. Wikipedia lists three methods to keep track of which articles are cross linked: Refback, Trackback, and Pingback. Of these, perhaps the trickiest to implement is the Pingback because it uses the xml-rpc style of communication rather than SOAP or REST that most .Net programme

Sending TrackBacks

Yesterday, I showed how we can receive trackbacks from other sites using the TrackBack API. Today, we'll look at the other side of this picture: sending TrackBacks to other sites based on links in the post. Sending a TrackBack entails several steps: Parsing the post to find links to other sites. Checking the target site to see if it supports TrackBacks. Formatting and sending the TrackBack to the target's service. Checking for error responses. Thus with every post I create now

Receiving Trackbacks

If you've been following along, I've been working on enhancing this site a bit recently. A couple of the most recent enhancements can be found in the following posts: Paging with AJAX WCF and LINQ Adding Gravatar support to comments Continuing in this tradition, I wanted to include the ability to be notified when other sites post links to my posts. There are several such API's that support this kind of notification, including Trackbacks and Pingbacks. In this post, we'll look at recei

Entity Framework Samples in Visual Basic

For those Visual Basic users out that that have struggled with the fact that the samples were only available in C#, you can now rejoice. There are a number of projects that have now been translated into Visual Basic for your learning pleasure. You can find these samples on the MSDN Code Gallery’s Entity Framework page. At this point the following projects have been translated. Entity Framework Query Samples Compatible with .NET Framework 3.5 SP1 and Visual Studio 2008 SP1 (Visual Basic and C#

Paging with AJAX WCF and LINQ

These days, it seems that every web site needs to have some use of gratuitous AJAX in order to stay on the bleeding edge. Since we didn't have any here yet, I thought I would throw some in for good measure. I liked the lazy loading of records instead of paging found on some sites, including the Google RSS reader and thought I would see what it would take to add something like that here. If you're not familiar with this paging option, instead of loading a new page of records each time the user

Adding Gravatar support to comments

Having a bit more free time than expected, I thought I would take a bit of time and add some features to this site based on some things I've seen at other sites. A quick one is adding Gravatar support to the comments. If you're not familiar with gravatar's, describes them as a globally recognized avatar, is quite simply an image that follows you from site to site appearing beside your name when you do things. To get a Gravatar, go to and let them know your email add

The real power of LINQ

At the Atlanta Code Camp, Michael Neal introduced me to something I didn't know about LINQ before. Since a picture says 1000 words, I thought I would just share the picture with everyone else. For those who haven't seen it yet, here's the true POWER of LINQ.

LINQ supported data types and functions

When we were writing LINQ in Action, we weren't able to specify all of the possible methods and functions that have supported query translations for a couple reasons. There were too many to be included in the scope of the book. The book was being written at the same time that LINQ was evolving and more comprehensions were being supported, thus giving us a moving target that we couldn't ensure the accuracy of when the product shipped. We realized that over time, translations for more funct

Changing the Namespace on generated Entity Framework classes

As I was preparing a presentation recently, I started hitting my head into a brick wall when trying to change the namespace on the entities generated by the Entity Framework. Having spent so much time with LINQ to SQL, I was anticipating that the behavior would be similar enough to make this easy. Unfortunately, I was mistaken. First, what I tried to do wrong. With LINQ to SQL, if you click the unused design surface, you can set the namespace for the Context separately from the Entities through

Win7 and the LINQ to SQL and LINQ to Entity designers

I've been playing with the Windows 7 Beta1 since they came out. So far, I've been really impressed with what I'm seeing. I've installed quite a bit and have put a full development environment on it including Visual Studio 2008 and SQL Server 2008. So far, the only real thing I've seen is a small bug in the LINQ to SQL and LINQ to Entity Framework design surfaces. In these, if you move the mouse over one of the entities on the designer, the entity may dissappear. There's a quick work-around fo

Selected for the INETA Speaker Bureau

I've been working with INETA as a user group leader and mentor to other user groups in the area. Recently I was honored to be selected to join an elite group of speakers as a member of their Speaker Bureau. If you lead a user group, contact INETA and let them know that you want to hear more about LINQ, let them know you want to hear from the Kinq! Bonus points if you're in a Mountain region. I feel honored to be part of this years new speaker list and glad to call many of them friends already.

Adding a dynamic SiteMap for search engine optimization using LINQ

A couple months ago I added a feature to this site to build a Site Map for this site dynamically based on the information from the database for posts and files for the downloads. If your not familiar with how Sitemap files can help your site searchability, Google has a good documentation about Sitemaps in their Webmaster tools. The SiteMap Protocal is a rather simple XML document consisting of a set of url nodes that consist of the following: loc - URL for the page link lastmod - Date

LINQ to Anything on Channel 9

I just had the pleasure of watching the Channel 9 video of Eric Meijer (Father of Haskel, champion of XML Literals, and leader of Volta) "interviewing" Bart De Smet (creator of LINQ to Sharepoint, LINQ to AD, and now LINQ to Simpsons). If you have a spare hour and want to dig into the guts of how IQueryable works, I definately recommend checking out the LINQ to Anything video. It's one of the most thorough yet approachable discussions I've seen on the topic. I'll have to watch it 3-4 more times

Updated source for ThinqLinq now available

It's been a while since I posted some serious content for which I apologize. I started this site a year and a half ago as a proof of concept around LINQ. When the site went live, I included the download version of the site from the presentations I've been doing on LINQ and Asp.Net. In all this time, I've made significant updates to the site, but haven't made them available, until now. If you're interested, you can download the updated bits from the file downloads here and play with them. I did t

LINQ is not an excuse for sloppy code

A couple months ago, I was convinced to try Twitter. In the process, I found which sends me notifications whenever someone tweets the word LINQ. Today I saw the following: "my visual studio crashed on retrieving 39,450 records via Linq.. what a shame.. looking for a workaround and a reason.." (name withheld to protect the guilty). In some ways, this falls into the category of, "Just because you can doesn't mean you should." In this case, the fault lies in the business requ

ThinqLinq on Deep Fried Bytes

Back at DevLinq (er DevLink), I had a chance to sit out on the back porch with Keith and Woody and chat about some of the cool features and rusty washers that you can find in LINQ. Head on over to and check out our conversation. You can also download the webcast to listen to on demand. Even better, you can listen on your Zune. As always, let me know what you Thinq.

TechDays 08 Atlanta

If you haven't signed up for Tech Days '08 Atlanta, what are you waiting for. Run on over to and sign up for 1, 2, or all 3 days. In addition to the posted conference, there's a series of chalk talks that are not on the official schedule. These are great ways to interact with experts at a level that is typically deeper than you get in the standard lecture type presentation. There are some interesting sessions which Glen has outlined on his blog. Here's the

Enabling intellisense for LINQ to SQL XML Mapping files

A while back, I showed you how to use an XML Mapping file to enable POCO support with LINQ to SQL instead of requiring you to clutter your class libraries with LINQ to SQL attributes. It turns out, the schema for the XML Mapping files (xmlns="") may not be included in your install of Visual Studio 2008. It was missing from mine. Luckily, the file is available on MSDN. If you add it to the schemas recognized by Visual Studio, you will get instant

Enable the Expression Tree Visualizer in VS 2008

In LINQ in Action, we discuss how to add the LINQ to SQL Query visualizer into the Visual Studio 2008 environment. This tool allows you to open a window during debug time to view the TSQL that is generated from the LINQ expression tree. It also allows you to run the query and view the results. If you're not familiar with it, check out this post by Scott Guthrie. In addition to the query visualizer, you can also build and install the Expression Tree visualizer, not only as a separate application

LINQ to Reflection IsNot LinqProvider

In one of the sessions I attended at DevLinq (er, DevLink), the presenter was discussing the providers that shipped with VS 2008. Among these, he included the standard LINQ to Objects, LINQ to XML, LINQ to SQL, LINQ to Entities and LINQ to Datasets. In addition, he added LINQ to Reflection which struck me as unusual, so I looked it up. In this case, LINQ to Reflection isn't really a provider, but just a specific implementation of LINQ to Objects which happens to query reflection informat

Object Identity tracking changes with LINQ to SQL SP1

When we wrote LINQ in Action, we took a bit of time to explain how the identity tracking system worked with LINQ to SQL to make sure that changed objects were retained when subsequent queries are requested from a data context. In a nutshell, when you issue a query, the data context translates the LINQ query into TSQL and sends that to the database. The database returns the rowsets to LINQ to SQL. The provider checks the returned rows against those that it is already tracking from previous fetche

Where clause optimized with VB 2008 SP1

There are subtle differences between VB and C# in terms of nullability. This caused a significant difference in the TSQL generated on even simple LINQ queries. Consider the following query from Northwind's Orders table where the Freight column is generated as a Nullable(Of Integer) type: Dim filtered = _ From o In dc.Orders Where o.Freight > 100 Select o First the bad news: with the RTM of VB 2008, this query resulted in the following TSQL: SELECT [t0].[OrderID], [t0].

VB Ordering of Anonymous Type Properties change with VS 2008 SP1

The VS 2008 SP1 includes lots of new features (more than a typical service pack, but that's another matter). There are a number of smaller enhancements that could easily go un-noticed otherwise. One of these is to fix a bug in the way the VB compiler generates anonymous types. In most cases, you will only notice this if you are binding an anonymous projection to a DataGridView or the ASP GridView. With these controls, you will find that the columns used to be generated alphabetically rather th

Filling an object from a DataReader with LINQ using DataContext.Translate

One of the key things that LINQ to SQL does for us is offers a quick way to fill a set of objects with data from a database. Typically this is done by setting up some mapping and calling the GetTable method on the DataContext. There are cases, particularly when you already have an infrastructure set-up to populate objects using a DbDataReader, where it would be nice if you could just populate the columns without the need to set-up a mapping. The DataContext has a little known method called Tran

Geek Speak podcasts are back

Glenn just announced that the Geek Speak podcasts are available again. They were disabled right before my session on LINQ Migration Strategies came out. If you have a Zune or IPod and want to subscribe to the feed, it is available again.


While I was away on vacation, Wriju posted a good list of MSDN documents he calls the "LINQ to SQL Missing Manual". It is a good list and addresses a number of items people regularly ask about concerning LINQ. Perhaps the most important ones are: Customizing Insert, Update, and Delete Operations (LINQ to SQL)Describes how to add validation code and other customizations. Data Retrieval and CUD Operations in N-Tier Applications (LINQ to SQL) Provides detailed information for multi-tier applica

Fetching child records using Stored Procedures with LINQ to SQL

You can consume stored procs rather than the standard dynamic sql for accessing child objects. To do this, set up your fetch stored procs and make sure that they return the correct data type (not the standard custom generated type for stored procedures). To load a child collection, create a method on the partial implementation of your context. Name the function "LoadCs" where "C" is the name of the child property accessor from the parent object in the designer. This function will take a type as

LINQ is not about working with databases

I don't know how many people I've talked to about LINQ concerned that it requires direct table access. Ok people, repeat after me: LINQ is NOT about working with databases. LINQ is an abstraction layer for working with data which allows for set based operations, projections, filters, etc on anything that can be enumerated over. It just happens to have providers for working with relational data (LINQ to SQL, LINQ to Datasets, LINQ to Entities). Oh, BTW. Each of these providers support using St

Screen scraping and creating Word documents with LINQ to XML

At TechEd Developers 2008 in Orlando, I had the pleasure of competing in Speaker Idol. In that competition, we had the opportunity to present a topic in 5 minutes. Unfortunately, the topic I choose really needed 10 minutes to cover at the level of detail it needed. Instead of limiting the topic, I decided to go ahead and present it a bit too fast. If you want to see the video, or see how to use VB 9's XML Literals and LINQ to XML to fetch data from a web page (that must be XHtml compilant), ma

LINQ to SQL support for POCO

One of the strengths that LINQ to SQL has over the upcoming Entity Framework is its support for POCO, or Plain Old Class Objects. With LINQ to SQL, the framework doesn't require any particular base classes, interfaces or even reliance on the 3.5 framework for the resulting objects. I demonstrated this in the talk I did at the Teched Tweener weekend. Download the demo project to see this in action. In this sample, I created two separate projects. The first class library project, I created only t

ThinqLinq at TechEd Developers 2008

If you're at Tech Ed Developer in Orlando, make sure to find me. If you miss me on the convention floor, I'll also be participating in Speaker Idol on Wednesday 6/4 at noon. In addition, I will be doing a book signing in the store at 1:00 on Thursday, 6/5. As you can see from this picture, they have a couple copies of the book that you can buy if you didn't bring your copy. I look forward to meeting you.

Danny Simmons compares the Entity Framework to similar technologies

It seems that everyone else is chiming in on Danny Simmons' recent comparisons of the Entity Framework with other similar technologies. There are several items I wanted to address from his observations. Regarding the EF vs. LINQ to SQL, he makes two basic points: 1) That there isn't a provider model for other data sources and 2) That LINQ to SQL requires a 1-1 table to object mapping. On the second item, there is no denying the limitation. While you can work around the issue with LINQ to SQL's

Anonymous Type property ordering in VB

Many people have noticed when binding an anonymous type to a grid in VB that the order of the properties does not reflect the order that they were specified in the projection (Select) clause. Instead, they appear alphabetized. Consider the following query: Dim query = From c In Customers _ Select c.LastName, c.FirstName, c.BirthDate If you bind this query to a DataGrid or DataGridView and allow the columns to be generated automatically, the results will be displayed with the

Projecting into an unmapped property from a LINQ to SQL query

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. To begin, let's consider the Author table we have in the book samples. The Author class has separate fields for the first and last name. Each of these is mapped to the corresponding fields in the Author table. In the book, we show how you can create a read only property in a partial

Geek Speak discusses LINQ Migration Strategies

Tomorrow, Wednesday 4/2/2008, I will be the guest speaker on the Geek Speak webcast. We will be discussing strategies for beginning to incorporate LINQ into your existing application infrastructure. In many cases, that does not mean replacing your entire data stack, but rather using pieces of LINQ to add functionality and in new components. Please join us. The Geek Speak webcasts are often driven by attendee questions. The more questions, the better the event. When: Wednesday, April 02, 2008 12

Joining composite keys with LINQ

LINQ makes working with data in its various guises easier. By intergating it into the language, we have rich integrated support for working with data. However, there are times where the syntax is slighly different from what you would typically expect with TSQL. Once case where this occurs is when trying to join two data sources that are related by more than one field (also know as a composite key). This differs from standard joins where one table has a primary key and the other table has a forei

LINQ enabled Personal Web Starter Kit in C Sharp

I love it when projects take a life of their own. A while back, I posted my LINQ enabled Personal Web Starter Kit in VB and received several requests to provide a C# port. Thankfully, one brave soul stepped up and did the port for me. Thanks go to Stephen Murray for undertaking the challenge. As is often the case, one of the best ways to learn a technology is to use it. If you're interested in this sample, you can check out the project at the MSDN code center. Specifically, you can access the

Querying the complete plays of Shakespeare using LINQ to XML

I was working to come up with some creative uses of LINQ to XML for my new talk I'm giving at the Huntsville, AL Code Camp. I figured it would be good to include a sample which queries a large XML document. Remembering that the complete works of Shakespeare were available in XML form, I did a quick search and found a version at This file separates each play out into separate XML files. Since I wanted to find out which parts had the most lines acr

Managing self referencing tables with LINQ to SQL

Using a single self referencing table is a common database pattern for trees of data. As an example of this concept, we can use the Employee table in Northwind. It has a self referential relationship set up using the ReportsTo field. If we drag this into the LINQ to SQL designer, it will infer the self relation and create the appropriate EntitySet/EntityRef relationship exposing it with the Employees (for subordinates of a given employee) and Employee (for the reference to the boss). The Reports

LINQ Migration hints

So, you're thinqing about convering existing code to use LINQ? Here are a couple quick tricks to get you started: 1) Have your regression tests ready. No warrantee is implied as to your success once completing the following. 2) Find any imports to System.Data.SqlClient including global imports and remove them. See what breaks in your application and re-write it using LINQ to SQL instead of ADO. 3) Search for iteration loops (For Each/foreach) or explicit calls to enumerator.MoveNext and see

Personal Web Starter Kit LINQed up

In case anyone is interested, I have put together a sample port of the original Personal Web Starter Kit using LINQ rather than the standard ADO data tier in the PhotoManager.vb class. With this version, we can eliminate all of the stored procedures and rely on LINQ for our entire data access. In this implementation, I intentionally attempted to retain the original method signatures where possible to make migration more seamless. The project site is at

Consuming a DataReader with LINQ

Last night at the Atlanta MS Pros meeting, I gave the first my new talks on LINQ Migration Strategies. If you missed it, you can catch me at the Raleigh, NC and Huntsville, AL code camps. Baring that, check out the presentation slides. This talk focuses on how you can extend existing structures using the power of LINQ. Among other things, this includes LINQ to DataSets and the XML Bridge classes. During the presentation, fellow MVP, Keith Rome asked a question that I couldn't let sit. Is it pos

Dynamically extending LINQ queryies without building expression trees

As more content is added to this site, I wanted to add a searching function. The implementation here is relatively simple. We will parse the input string into the various words represented and perform a TSQL LIKE filter in the WHERE clause. Doing this on a single string is relatively simple. We just use the String.Contains method in the WHERE clause as follows: Dim query = From p in dc.PostItems _ Where p.Description.Contains(InputValue) _ Select p This

Comments are now LINQuiries

I was inspired by fellow MVP, Matt Kleinwaks to rename the comments tab of this site. Now, you can send feedback using the l-Inquiry tab. Don't be afraid to tell us what you Thinq.

Linq In Action going to press

At long last, the process of doing my first book is coming to a close. I started this project last March. Through the process we had to revisit our work numerous times, including each time a new CTP or Beta drop came. For me, 10 months, and Fabrice 2 years later, we found out this week that the book is going to press. What does this mean for you, if you purchased the eBook, the final version is available now. Additionally, the samples are available online in both C# and VB. We are also making t

Adding categories to the RSS feed using LINQ to XML

Last time, we added categories to the web view of the ThinqLinq site. This time, we're going to add them to the RSS feed. Because RSS is "Really Simple", adding the categories is fairly easy. According to the RSS specification, <category> is an optional sub-element of <item>. It can additionally contain the domain that contains that category. In our case, we will point the domain to our implementation that displays all posts for a given category by passing the category id to the quer

Adding a RSS feed for file downloads

Ok, so I've been a bit busy this weekend adding some nice stuff for this site. One thing that I wanted to add was another RSS feed, this time for the file upload section. If you want to subscribe to the File RSS feed, direct your aggregator to the following link: Of course, since this is a learning site, I'll let you in on the code needed to accomplish the task. As you may guess, LINQ makes serving up XML from an object collection using a heterogeneous jo

Binding Many to Many relationships using nested repeaters with LINQ

Last time, we looked at the structure of the ThinqLinq posting items to see how we could extend the RSS feed limiting the output by categories. This time, we are going to look at extending the standard post output on the site to display the categories for each post. When we set categories and posts up, we created a many-to-many relationship between the posts and categories using an intermediary CategoryPost table and object collections. When dealing with many to many relationships with object h

Filtering items in the ThinqLinq aggregation feed

When I first released ThinqLinq, the only filtering I applied was to only select the top 20 posts. I was recently asked if I could extend the implementation so that it the aggregation feed could be filtered based on the categories. Since ThinqLinq uses LINQ for the data interaction, it is relatively easy to add filtering to the existing query. However, in this case, the filtering is not a simple Where clause on the underlying table. That is because the table structure uses a Many to Many relat

Welcome to ThinqLinq

You may have seen me present it at a speaking engagement. You may have watched the podcasts. You may have even downloaded the sample application. Now you can see it in action. is now live. The site was designed completely in VB with LINQ as the data access mechanism. The base application was built in 2 hours from not knowing RSS to being able to import a RSS feed, displaying it on a form and producing a new feed from the imported data. The site is a testimate to the power of LIN

Using LINQ to SQL to return Multiple Results

In the LINQ in Action forum, a user asked about returning multiple result sets from a single stored procedure. Below is one way of dealing with this issue. In the procedure, we used multiple results rather than a result with a return value (through RETURN or an OUTPUT parameter). Here we need to use the IMultipleResult rather than the default ISingleResult implementation. It appears that the designer does not map IMultipleResult in the final build, so we are going to need to do it ourselves. We

LINQ In Action Samples online

It's the time of the year when we put the finishing touches on our decorations. As Fabrice annouced, we are in the same mode with our book. The text is almost ready, but you won't be able to get the hard copy under your tree this year unfortunately. If you can't wait, you can download the samples in both C# and VB now. We'll let you know when the book starts shipping. If you don't want to wait, you can pre-order it through Amazon, or purchase the ebook/print combo directly through Manning.

More on VS 2008 breaking changes

In addition to the items I mentioned in my previous Beta 2 - RTM breaking change list, I found a link on the VS 2008 samples page that a whitepaper has been issued on this. Download the whitepaper at this link: In addition, there is a whitepaper specific to breaking changes between VB 2005 and VB 2008 available here.

Visual Studio 2008 Orcas Changes from Beta 2 to RTM

I've just updated the ThinqLinq proof of concept site for the Visual Studio 2008 release that came out today. If you're following the sample application, or are looking for a sample VB 9 implementation of LINQ in a web site, check out the download at In case you are interested, here are the changes that were necessary to move from Beta 2 to the RTM. (The first two items are repeats from my post earlier today). Open the DBML file as X

Projecting XML from LINQ to SQL

Among the new cool features in Visual Studio 2008, one of the best may be the XML Literal support with VB 9 and LINQ. In my last post, I mentioned some changing features from the Beta to RTM. One that could easily be overlooked is a change to the way LINQ to SQL can now directly project into XML literals. Through the Beta cycle, there was an issue with projecting XML elements directly from a LINQ to SQL query. If you haven't seen LINQ to SQL with XML, here's a code sample that explains what I'

Creating HTML emails using VB 9 and LINQ

Today, I'm not looking at sending mass spam using LINQ to pull a list of recipients. I'm actually referring to the ability to generate the message body using XML Literals. Using the System.Net.Mail.MailMessage object, we can easily send emails to an SMTP server. The body of the email can either be plain text or HTML. Dynamically generating the text is often a laborious task involving a string builder and lots of method calls. The body corresponds to the body portion of a HTML page. If you use

Adding RSS posts to ThinqLinq using System.ServiceModel.Syndication.SyndicationFeed

When I originally started the ThinqLinq project I began by loading the RSS feed from my DevAuthority blog, and iterating over the results adding them to the PostItems table in the data context. With LINQ this is relatively easy. Loading the XML from the feed is done with a single line: Dim Feed As System.Xml.Linq.XDocument = _ XDocument.Load("") The xml document consists some basic informational elements which are not terribly important in this instance as w

Code Camp 2007 downloads

I've uploaded the files for my presentations for the fall Code camp season which I just presented last weekend at the Birmingham, Alabama code camp. If you missed the talks, you can pick up the downloads at the following links. Also, I will be at the Charleston, South Carolina code camp this coming weekend (10/13) so you can catch me there. Additionally, the ThinqLinq talk is still available on the Links to all three parts of the webcasts are available on the file download pa

LINQ to SQL Compiled Queries

As LINQ nears release, people are starting to consider the performance implications that the extra overhead brings. Currently there are two threads on this: thread1, thread2. For those that are intested in the performance implications, I highly recommend checking out the outstanding series of posts by Rico Mariani. Ultimately if you want to get the best performance, you need to use the Compile function of the CompiledQuery class. Let's consider the following query (Note, turn this into C# by a

Use the new LINQ Contains extension method for the SQL IN clause

For a while, users were requesting a way to map the SQL "IN" clause as in the following: SELECT Customer.Name FROM Customer WHERE Customer.State IN ('GA', 'FL', 'AL') Prior to Beta 2, this would mean either separate OR clauses for each item, or worse yet a heterogeneous join between the database and an in memory array. Why do I say, worse yet? Because the heterogeneous join option meant bringing all of the records from the database and filtering on the client. Beta 2 introduced a new "Cont

DataLoadOptions replaces DataShape

As I continue updating my projects to Visual Studio 2008 Beta 2, I found yet another namespace change. This time, it's not the namespace, but object name that has changed. With Beta 1, we could specify what objects would be loaded automatically with their parents using the DataShape object that you attach to the DataContext. Here is a bit of code that would load a set of books whenever the associated subject was loaded. This would have the benefit of not lazy loading each child collection and

LINQ to SQL changes from Orcas Beta 1 to Visual Studio 2008 Beta 2

I've been working this weekend trying to get my samples for the upcoming Linq In Action book and other demos up and running with the recent Beta 2 drop. Below is a summary of some of the changes that I needed to make. In general, if you are able, I would recommend dumping your data mapping file (dbml) and creating it again at this point as there are lots of changes both to the XML schema and the generated code. If you don't have that luxury, be prepared for a lot of work at this point. Dinesh h

ThinqLinq webcast series part 3 is available

Part 3 of the Thinq Linq webcast is now available at This is the third (and for the moment final) installment of the series discussing using LINQ to create the blogging web site, In this session, we focus on the new XML features of LINQ, including XML Literals. In the end we see how easy it is to use a LINQ to SQL query to return blog pos

Thinq LINQ webcast part 2 now available

Part 2 of the Thinq Linq webcast is now available at I'm pretty happy with this one in particular. It covers a couple key pieces of LINQ that aren't discussed much: Heterogeneous joins Updating disconnected data using LINQ. The LINQ to SQL designer Using an XML mapping source instead of attributes. The presentation quality was a bit dif

Thinq LINQ webcast series part 1

Back at the Mobile Code Camp in March, Wally McClure asked if I would be willing to record my session for his AspnetPodcast site. Technical details kept me from recording that session, but I did record the same presentation later that week at the Atlanta VB Study Group's meeting. Now you can see it as well. Head on over to and check out the first of 3 part

WCF with the LINQ to SQL designer

A frequent question on the LINQ forums regards how to combine LINQ with a service oriented application. The main issue is that the DataContext which sits at the core of LINQ to SQL in managing the connection and change tracking is not intended to be remoted. In addition, the DataContext should be rather short lived in a disconnected environment (including ASP). With the addition of WCF in the 3.0 framework, the question of how to enable LINQ to SQL entity definitions to participate in a WCF Data

LNQ to SQL with Inheritance

Working on a side project extremely late last night, I found myself trying to count sheep. In particular I was interested in separating the males from the females. Using good OOP principals, I figured I could create a base class "Sheep" and inherit from that for the "Ram" and "Ewe" classes. Below is a simplified class model: In order to map this to a LINQ to SQL class model, we can simply define the three classes, Sheep, Ram and Ewe. We place the standard <column> attributes on the col

Changed order of LINQ operators for VB 9

With the March Orcas CTP, the order of operations has changed for VB LINQ Queries again. No, they have NOT moved Select back to the beginning. In this case, they have moved the Order By clause before the Select. In case you prefer a bit of code consider the following: May 2006 CTP: dim res = From fi in New System.IO.DirectoryInfo("C:\").GetFiles() _ Select fi _ Order By LastAccessTime March 2007 CTP: dim res = From fi in NEw System.IO.DirectoryInfo("C:\").GetFiles

Linq Geek Speak available

A couple weeks ago, I had the privledge of discussing my favorite topic, LINQ, in an MSDN Geek Speak. If you missed it, they posted a recording of it today. Check it out at Also, you can check out the LINQ Links at (Yes, I know they spelled my name wrong in the URL.) Speaking of names, what do you t

Geek Speak this Wednesday

Local Community Champion, Glen Gordon convinced me to share my LINQ insights in an open chat forum this Wednesday, 1/10. If you are interested in LINQ, sign-up for the talk at and check it out. Here's the link to the annoucment on their blog:

Using LINQ to query against objects and XML

In preparing for my LINQ talk for DBA's at tomorrow's Atlanta Microsoft Database Forum user group meeting, I thought it would be good to offer a quick look at the LINQ to Objects and LINQ to XML stacks before focusing on the OR mapping portions: LINQ to SQL, LINQ to Entities and LINQ to dataSet. I previously used a quick demo which joined the FileInfo collection returned by DirectoryInfo.GetFiles with an object collection built from a CSV file. For this demo, I wanted to add in the XML stack.

Use LINQ to convert CSV to XML

File conversion is a typical programming task. VB9 should make this task easier to code and maintain as we can eliminate much of the plumbing code and focus on the task at hand. The following example uses the MAY CTP of LINQ and leverages the TextFieldParser added to VB 8 to convert a simple CSV file to XML. For this sample, we will convert a simple CSV file that contains standard windows file extensions with a brief description of the file. Here are the first couple of lines: .doc,Microsoft

Montgomery Code Camp Files available

I had the pleasure of heading over to Alabama for my last code camp of the year last month. I posted the files from my presentation but neglected to post a link to the files here. The VB 9/C# 3 talk was the same that I have given over the past year. This time, I also presented my first look at LINQ to SQL (formerly DLINQ). You are free to download the slides and demos at You get everything from the presentation except for the 30,00

Querying Winforms with LINQ

A couple of months ago, someone asked on one of the forums how you could dynamically switch a control from a textbox to a label based on the editability of the record based on business requirements. The best solution was to change properties on the textboxes to make them look like labels. Below is a quick method to do this: Private Sub SwitchControl(ByVal box As TextBox) If box.ReadOnly Then box.BorderStyle = BorderStyle.Fixed3D Else box.BorderStyle = BorderStyle.None End If b

ASP Security is more than just SQL Injection

Last night's Atlanta Microsoft Database Forum meeting had another discussion of SQL Injection and how it is a bad thing. In the end, the best thing to do to avoid it is to use parameterized queries (which include, but are not limited to Stored procedures). In short, if you write your data access code in your application like the following, you are prime for an attack: dim stSql as string = "select * from users where userid='" & Request("UserId") & "'" Instead, take a little more care an

LINQ to Foo

Soma just announced some additional re-branding of some of the LINQ stack. In addition to LINQ to SQL and LINQ to Entities, which were announced at Tech Ed, the ADO.Net stack will include LINQ to DataSet. Additionally, standard LINQ is being branded as LINQ to Objects, and XLINQ will now be LINQ to XML. (There goes I suppose) Personally, I have no problems with the proposed change and think it makes perfect extensible sense. I previously wrote where this naming would be ideal and see i

LINQ Webcast online

Last month, WROX press recorded several of the sessions at the Atlanta Code Camp, including mine on how the language changes in VB 9 and C# 3 lead to LINQ. If you missed the talk, you can now watch it online at I haven't had a chance to watch the whole thing yet, but from what I saw so far it looks like they did a pretty good job with it, including indexing the talk. Check it out and let me know what you think.

DLINQ Renamed

As is typical at Microsoft conferences, they have a way of announcing code name changes. Yesterday, they renamed WinFx. Today, Andres Aquiar stated that DLINQ is being changed to "LINQ to SQL". In addition, they are working on "LINQ to Entities" which is reference to a mysterious Ado.Next document that was published and then pulled within hours of being released. For those of you who are interested in how the two fit together, I recommend checking out the Channel 9 video at h

LINQ over Datasets or the Bang is back in VB9

One of the features that was added to the May CTP of LINQ was the ability to query over DataSets. There are some minimal methods of manipulating data in existing implementations of the DataSet, including filtering with DataViews, the .Filter method and using DataTable.Select(). If you wanted to work with multiple tables, you needed to use a DataViewManager object. The overview of these options is online on Msdn. One of the new features of the May CTP of LINQ includes the ability to create queri

LINQ Links

I typically try to avoid making link blog posts, but wanted to call your attention to a couple good posts recently regarding LINQ. The Microsoft XML team just put up a good collection of links. I agree completely with the initial statement that the community seems to be focused on DLINQ to the exclusion of the other pieces of the puzzle, namely LINQ and XLINQ. There could be any of a number of reasons for this. My top ideas are: DLINQ is wanted because ADO is too cumbersome and people want a

Atlanta Dotnet User Group does LINQ

On Monday I presented LINQ 101 to the Atlanta Dotnet User Group. There was a good reception for the presentation and around 60 people attended. I was surprised that 1/4 of them were already familiar with LINQ. I look forward to doing a 200 level talk at the Atlanta Code Camp in May. The best moment of the night for me was when I took a standard For Each (foreach) iteration and changed it to a LINQ query expression. I could hear some jaws drop from the front of the room. You can download the sli

Alabama Code Camp

I did my first 2 talks on LINQ this past week. On Saturday I presented for the Alabama Code Camp. Unfortunately, I was on the last slot of the day and a number of people left early. Additionally, I was up against Doug Turnure's Memory Management talk (who would have thought he would have standing room only for that talk). The turn out for Monday's Atlanta DotNet meeting was better. Any way, I'm uploading the slides, sample projects, and code script for attendees to check out. Feel free to chec

DLinq Extension Methods Decomposed

A recent inquiry on the DLinq forum ( asked why the .ToArray method was not being recognized in DLinq. Actually, the issue they were seeing was a message that their array object (db.Customers) didn’t have a .ToArray method. While the compiler is correct, it does not point to the true source of the problem. This is due to the magic of the Extension Methods. The sample that was in question is as follows: Northwind db = new