Click here to Skip to main content
15,897,371 members
Articles / Programming Languages / C# 4.0

Entity Framework Patterns: Select Multiple Entities

Rate me:
Please Sign up or sign in to vote.
4.69/5 (26 votes)
16 Dec 2010Ms-PL4 min read 175.4K   1.1K   47  
Introduce different patterns in Entity Framework around selecting a list of entities.
using System;
using System.Collections.Generic;
using System.Linq;

namespace TestPatterns
{
	/// <summary>Entry point in the application.</summary>
	class Program
	{
		static void Main(string[] args)
		{
			var idList = GetIDList();

			Console.WriteLine("Selected IDs:");
			foreach (var id in idList)
			{
				Console.WriteLine(id);
			}

			//var orders = SelectingEach.DoSelect(idList);
			//var orders = DoingUnion.DoSelect(idList);
			var orders = DoingWhereIn.DoSelect(idList);
			//var orders = JoiningOnAnotherTable.DoSelect(idList);

			foreach (var o in orders)
			{
				Console.WriteLine("Order:  {0}, Detail Count ({1})", o.OrderID, o.OrderDetail.Count);
			}
		}

		/// <summary>Pick three ids out of the DB.</summary>
		/// <returns></returns>
		private static int[] GetIDList()
		{
			using (var context = new EFDemoEntities())
			{
				var random = new Random();
				var orderIDs = (from o in context.Order
								select o.OrderID).ToArray();
				var randomizedIDs = from id in orderIDs
									orderby random.Next()
									select id;
				var selectedIDs = randomizedIDs.Take(3).ToArray();

				return selectedIDs;
			}
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Architect CGI
Canada Canada
Vincent-Philippe is a Senior Solution Architect working in Montreal (Quebec, Canada).

His main interests are Windows Azure, .NET Enterprise suite (e.g. SharePoint 2013, Biztalk Server 2010) & the new .NET 4.5 platforms.

Comments and Discussions