Saturday, December 12, 2009

Entity Framework query

Three examples of doing a simple select operation - one using standard entity framework, one using Linq to Entities, one using a lambda expression.

//example using entities. No filtering of the data.
var books = context.Book;
foreach (var book in books)
{
    Console.WriteLine("{0} {1} {2}", book.Author, book.Title, book.URL);
}

//example using Linq to entities. Adding in a where clause to filter out the data a bit

var booksLinq = from b in context.Book
                          where b.Author.Contains("Brown")
                          select b;

foreach (var item in booksLinq)
{
      Console.WriteLine("{0} {1} {2}", item.Author, item.Title, item.URL);
}

//example using lambda
var booksLambda = context.Book.Where(c => c.Author.Contains("Brown"));
foreach (var book in booksLambda )
{
      Console.WriteLine("{0} {1} {2}", book.Author, book.Title, book.URL);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.