Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Entity Framework 4 New Operations

4.50/5 (2 votes)
14 May 2010CPOL3 min read 17.9K  
There are some new operations in .NET 4 Entity Framework. This a quick example of each working with VistaDB 4 and Visual Studio 2010.

There are some new operations in .NET 4 Entity Framework. This a quick example of each working with VistaDB 4 and Visual Studio 2010. These changes were mostly made to bring LINQ to Entities inline with the other LINQ providers in .NET. Of the list below, I think that Single() was the one that most people were confused about because if you used it, you would get weird errors that didn't make a lot of sense.

For a complete list of LINQ to Entities operators, visit the Supported and Unsupported LINQ Methods on MSDN.

Entity Framework in .NET 4

The operations I want to demonstrate are the new Contains(), Single(), SingleOrDefault(), and DefaultIfEmpty().

SimpleTable for Entity Framework Example

These operations are all new in .NET 4, and yes they work with VistaDB 4. I started with a simple one table database called Feedback. The only table has 3 columns:

  • int FeedbackID
  • NText FeedbackText
  • DateTime FeedbackDate

I added a few small text entries, including “I like grapes'” to search against with the Contains() operator.

Adding the Entity Framework Model

Simple EF Model

I then added an Entity Framework to a simple command line application set with .NET 4 as the target in Visual Studio 2010.

The model is only that one table, no navigation or anything complicated.

This model was called FeedbackEntities. Each model with Entity Framework requires you to allocate this Data Context object to perform queries against the database.

This sample model can be created using the following C# code:

C#
using (FeedbackEntities fe = new FeedbackEntities())
{
    // Code here
}

Complete Entity Framework Sample Code

Here is the complete sample code for the operations against that database:

C#
static void Main(string[] args)
{
    using (FeedbackEntities fe = new FeedbackEntities())
    {
        // Contains - returns a collection of comments - even if only 1 present
        var grapecomment = from f in fe.Feedbacks
                            where f.FeedbackText.Contains("grapes")
                            select f.FeedbackText;

        Console.WriteLine( grapecomment.First() );

        // Demonstrate Single() on that same contains, you don't need the .First() 
        var oneresult = (
                            from f in fe.Feedbacks
                            where f.FeedbackText.Contains("GRAPES") 
                                select f.FeedbackText
                            ).Single();
                
        Console.WriteLine(oneresult);

        // Demonstrate SingleorDefault on FeedbackText
        var singleordefault = (
                                from f in fe.Feedbacks
                                where f.FeedbackText.Contains("grapes")
                                select f.FeedbackText
                                ).SingleOrDefault();

        // Only 1 will be returned, or the default for the type (could be null)
        Console.WriteLine(singleordefault);

        // DefaultIfEmpty will return text if nothing is found, as a collection
        var notfound = ( 
                        from f in fe.Feedbacks
                        where f.FeedbackText.Contains("xxxxxxxx")
                        select f.FeedbackText
                        ).DefaultIfEmpty("Not found");

        // We have to select First() because a collection was returned 
        Console.WriteLine(notfound.First());
    }
}

Contains

Contains() does a case insensitive compare for parts of the word in that field. You will notice that I had to do a .First() on the grapecomment because the select returns a collection, even if there is only one item in the collection.

Single

Single() is used in the next example on the same query, but this time you only get back one item. This means you don’t need the .First() from the first example.

SingleOrDefault

Returns back a single object, OR the default for that object. This means if it is a complex type, you could get back a null. In this case, we get the same result.

DefaultIfEmpty

I changed this example to search for an item that does not exist on purpose. The DefaultIfEmpty() will then return whatever you pass into it as the result. This means we will not find the result, and return “Not found” as the string rather than a string.Empty. But note that this is now a collection again, so it prints it. We have to take the First() item of the collection.

Sample Output

This is what is returned by the above code:

I like grapes 
I like grapes 
I like grapes 
Not found

Summary

There are a lot of operations you can perform through LINQ to Entities with an Entity Framework model. These are only a few of the new operations in .NET 4. See the Standard Query Operators Overview for more information.

I will put this sample up in the VistaDB 4 Samples Forum for those who want to download it and test it themselves.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)