Blogs

Paul Kimmel's Blog

February 2009 - Posts

  • Adding Generic Anonymous Delegates to LINQ Anonymous Types

         

    For those that know a little bit about LINQ its understood that LINQ returns Enumerable<T> objects as the result of a LINQ query. And, many of you experiment with .NET 3.5 probably know is that LINQ supports projecting new, anonymous types. A project is where you end the query with select new {} and list the fields from the originating type to be in the result type. What may not be obvious is that you can add methods to projected anonymous types. In short, this means that you can add methods to dynamically created new types.

    In the example I used LINQ and Visual Studio's object relational mapping capability with LINQ to SQL to create LQIN to SQL entity types for a Customer. Using a DataContext--also generated withe LINQ to SQL--a generic delegate Func<T,T> was defined that accepted two strings and concatenated the result. This generic delegate is then assigned to a named property in the projection of the select clause of the LINQ query. When the result set is iterated over and displayed the anonymous delegate is called like any other method (refer to Listing 1).

    Listing 1: Define a generic delegate and assign it to a projection to add methods to projected anonymous types.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace LinqToSQLBlog
    {
      class Program
      {
        static void Main(string[] args)
        {
          CustomersAndOrdersDataContext context =
            new CustomersAndOrdersDataContext();

          context.Log = Console.Out;
          Func<string, string, string> stringizer =
              delegate(string title, string name){
                const string mask = "{0}, {1}";
                  return string.Format(mask, name, title);
               };

          var customers = from customer in context.Customers
                          select new
                          {CompanyName=customer.CompanyName,
                           ContactName=customer.ContactName,
                           ContactTitle=customer.ContactTitle,
                           Address=customer.Address,
                           City=customer.City,
                           Region=customer.Region,
                           PostalCode=customer.PostalCode,
                           Phone=customer.Phone,
                           ToContact = stringizer
                          };

          Array.ForEach(customers.ToArray(),
            c=>Console.WriteLine(c.ToContact(c.ContactTitle, c.ContactName)));
          Console.ReadLine();     

        }
      }
    }

    By default when you create a projection the ToString method is provided to dump all of the properties of the new type. In the example ToContact was added to display a formatted output that displays the contact name and title. You can accomplish a similar result by adding an extension method and replacing ToContact in the Console.WriteLine call with the extension method (ToContact2) in the helper class. Listing 2 contains the definition of the extension method (and its class).

    Listing 2: An extension method that will work with the anonymous projection too.

    public static class Helper
      {
        public static string ToContact2<T>(this T table,
          string title, string name)
        {
          const string mask = "{0}, {1}";
          return string.Format(mask, name, title);
        }
      }

    Really getting as many aspects of the .NET Framework is critical to becoming inventing with how you use the framework. Although all of the examples are short, the CodeDOM, generics, generic delegates, Lambda expressions (c=>Console.WriteLine...) and extension methods were all employed in crafting the solutions.

    If you this post helped you add a comment. If you want more juicy tidbits like this one then check my blog or check out my book LINQ Unleashed for C# from Sams.

  • LINQ to SQL

         

    LINQ to SQL can be an excellent keystone to mastering LINQ at a deep conceptual and technical level. Think about it. LINQ (pronounced "link"), or Language INtegrated Query, is an integrated query language that lets you manipulate everything from objects to databases to XML, and LINQ can be extended into other areas like SharePoint and Active Directory. Consider LINQ to SQL. LINQ is its own query language. When used with SQL LINQ converts code-queries into SQL on the fly. Understanding how to write LINQ queries is a good beginning. Mastery comes with grokking how LINQ might convert its queries into SQL queries. With this mastery comes the ability to use LINQ and extend LINQ into new spaces like Active Directory.

    The fundamental reason you would choose LINQ over SQL for data, XPath for XML, C# or VB for code, and dsquery for Active Directory (and whatever else you can think of) is that LINQ is a "learn once, apply many" (times and ways) kind of technology.

    When using LINQ to SQL you can begin by adding a LINQ to SQL Classes element from the Add New Item dialog (a .dbml file). Drag a couple of tables from the Server Explorer onto the object relational designer--like Northwind Customers and Orders--and the object relational designer (see Figure 1) will infer the association and use the CodeDOM to code generate smart entity classes. (You can generate an object relational map to explore the generated code.) At this point you need to create a context, which is analogous to a SqlConnection, and query away. Use LINQ to read data and context methods to write data.

    image
    Figure 1: The Visual Studio object relational designer will infer relationships and code generate entity classes; all you have to do is drag and drop tables from the Server Explorer.

    Listing 1 demonstrates how easy it is to query the Northwind (or any SQL database with LINQ to SQL). Just a few lines of code and you are off to the races. What is worth noting here is that I assigned Console.Out to the DataContext.Out property letting LINQ to SQL show us a bit about what its doing (see Figure 2). (If you want exhaustive detail about how all of this works check out my book LINQ Unleashed for C# from Sams. And, consider writing a review if you like it.)

    Listing 1: Reading data with LINQ to SQL takes just a couple of lines of code; all of the ADO.NET plumbing is managed for you.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace LinqToSQLBlog
    {
      class Program
      {
        static void Main(string[] args)
        {
          CustomersAndOrdersDataContext context =
            new CustomersAndOrdersDataContext();

          context.Log = Console.Out;

          var customers = from customer in context.Customers
                          where customer.CompanyName.StartsWith("A")
                          select customer;
          Array.ForEach(customers.ToArray(),
            c=>Console.WriteLine(c.CompanyName));
          Console.ReadLine();     

        }
      }
    }

    image
    Figure 2: Notice that LINQ is sending some information about its internal workings--the LINQ to SQL conversion--to the console.

    How does LINQ do it. The answer is that the .NET framework contains an interface for LINQ called IQueryProvider. IQueryProvider is a small interface. It defines two methods: CreateQuery and Execute. CreateQuery accepts input and you make substitutions using the expression tree capability of LINQ and Execute runs the query represented by the expression tree. If you are interested in LINQ to SQL relative to IQueryProvider start exploring Table<TEntity>'s implementation of IQueryProvider using Reflector's disassembler feature.

  • LINQ Today

         

    Language INtegrated Query (aka LINQ) is a great technology. Having written a book LINQ Unleashed and used LINQ for quite some time, I think LINQ is ready for prime time. However, there are technologies into which LINQ has been extended that have given me pause (and, in a couple of cases, fits).

    LINQ to objects, LINQ to XML, LINQ to SQL all work great and are great places for LINQ to be. LINQ to Entities (the Entity Framework) and Entity SQL are still a little wonky to me. Don't get me wrong, in the case of the Entity Framework, I believe Microsoft will make improvements but right now it is a bit challenging. In the case of Entity SQL (eSQL), I am not even sure why it exists. LINQ is clearly the key new technology, which makes eSQL superfluous (unless I am missing something).

    Like you, I have to learn the Entity Framework and master it, so sometimes I am not sure if it's me or EF. (I am in the process of writing a book on it, and I find EF "challenging" at times.) In order to help you I am going to stick my neck out a bit and offer some friendly advice: leverage LINQ to the hilt, don't spend a lot of brain cycles on eSQL, and don't bet the farm, your reputation, or your job on the Entity Framework just yet. (When my book is finished I hope a new version of EF will be available, and many of the kinks or challenges will be worked out for you. Watch out for Teach Yourself the ADO.NET Entity Framework in 24 Hours from Sams.)

    I am going to do several additional posts on LINQ, EF, and, yes, eSQL. Check back here, comment on the posts, or drop me a line at paulk@devexpress.com.

More from DevExpress
Live Chat
Have a pre-sales question?
Need assistance with your evaluation?
We are here to help.
Chat is one of the many ways you can contact members of the DevExpress Team. We are available Monday-Friday between 8:30am and 5:00pm Pacific Time.
If you need additional product information, require pre-sales assistance, or want help with your order, write to us at info@devexpress.com or call us at
+1 (818) 844-3383.