Using Entity Framework with an Existing Database: User Interface

Pre-existing databases can pose some difficulties for software developers using an ORM. To demonstrate ways of circumventing  them, Jon Smith builds an ASP.NET MVC application  with Entity Framework (EF) to provide a user interface to Microsoft’s AdventureWorks sample SQL database. He shares his design approach for displaying and updating this data with real examples from the test web application he built.

Read full article: https://www.simple-talk.com/content/article.aspx?article=2108

Hope this will help !!!
Jay Ganesh

Parallelism in .NET – PLINQ

Introduction

Most .NET developers today are familiar with LINQ, the technology that brought functional programming ideas into the object-oriented environment. Parallel LINQ, or ‘PLINQ’, takes LINQ to the next level by adding intuitive parallel capabilities onto an already powerful framework.

PLINQ is a query execution engine that accepts any LINQ-to-Objects or LINQ-to-XML query and automatically utilizes multiple processors or cores for execution when they are available. The change in programming model is tiny, meaning you don’t need to be a concurrency guru to use it.

Using PLINQ is almost exactly like using LINQ-to-Objects and LINQ-to-XML. You can use any of the operators available through C# 3.0 syntax or the System.Linq.Enumerable class, including OrderBy, Join, Select, Where, and so on.

LINQ-to-SQL and LINQ-to-Entities queries will still be executed by the respective databases and query providers, so PLINQ does not offer a way to parallelize those queries. If you wish to process the results of those queries in memory, including joining the output of many heterogeneous queries, then PLINQ can be quite useful.

Using AsParallel method :

The AsParallel method is the doorway to PLINQ. It converts data sequence into a ParallelQuery. The LINQ engine detects the use of a ParallelQuery as the source in a query and switches to PLINQ execution automatically. You are likely to use the AsParallel method every time you use PLINQ.

Sample code 1 : Sequential LINQ execution


	var customers = new[] {
		new Customer { ID = 1,  FirstName = "Sandeep"  , LastName = "Ramani" },
		new Customer { ID = 2,  FirstName = "Dharmik"  , LastName = "Chotaliya" },
		new Customer { ID = 3,  FirstName = "Nisar"    ,  LastName = "Kalia" } ,
		new Customer { ID = 4,  FirstName = "Ravi"     , LastName = "Mapara" } ,
		new Customer { ID = 5,  FirstName = "Hardik"   , LastName = "Mistry" }
		new Customer { ID = 6,  FirstName = "Sandy"    , LastName = "Ramani" },
		new Customer { ID = 7,  FirstName = "Jigar"    , LastName = "Shah" },
		new Customer { ID = 8,  FirstName = "Kaushal"  , LastName = "Parik" } ,
		new Customer { ID = 9,  FirstName = "Abhishek" , LastName = "Swarnker" } ,
		new Customer { ID = 10, FirstName = "Sanket"   , LastName = "Patel" }
		new Customer { ID = 11, FirstName = "Dinesh"   , LastName = "Prajapati" },
		new Customer { ID = 12, FirstName = "Jayesh"   , LastName = "Patel" },
		new Customer { ID = 13, FirstName = "Nimesh"   , LastName = "Mishra" } ,
		new Customer { ID = 14, FirstName = "Shiva"    , LastName = "Reddy" } ,
		new Customer { ID = 15, FirstName = "Jasmin"   , LastName = "Malviya" }
		new Customer { ID = 16, FirstName = "Haresh"   , LastName = "Bhanderi" },
		new Customer { ID = 17, FirstName = "Ankit"    , LastName = "Ramani" },
		new Customer { ID = 18, FirstName = "Sanket"   , LastName = "Shah" } ,
		new Customer { ID = 19, FirstName = "Amit"     , LastName = "Shah" } ,
		new Customer { ID = 20, FirstName = "Nilesh"   , LastName = "Soni" }       };

	var results = from c in customers
		      where c.FirstName.StartsWith("San")
		      select c;

Sample code 2 : Parallel LINQ execution


	var customers = new[] {
		new Customer { ID = 1,  FirstName = "Sandeep"  , LastName = "Ramani" },
		new Customer { ID = 2,  FirstName = "Dharmik"  , LastName = "Chotaliya" },
		new Customer { ID = 3,  FirstName = "Nisar"    ,  LastName = "Kalia" } ,
		new Customer { ID = 4,  FirstName = "Ravi"     , LastName = "Mapara" } ,
		new Customer { ID = 5,  FirstName = "Hardik"   , LastName = "Mistry" }
		new Customer { ID = 6,  FirstName = "Sandy"    , LastName = "Ramani" },
		new Customer { ID = 7,  FirstName = "Jigar"    , LastName = "Shah" },
		new Customer { ID = 8,  FirstName = "Kaushal"  , LastName = "Parik" } ,
		new Customer { ID = 9,  FirstName = "Abhishek" , LastName = "Swarnker" } ,
		new Customer { ID = 10, FirstName = "Sanket"   , LastName = "Patel" }
		new Customer { ID = 11, FirstName = "Dinesh"   , LastName = "Prajapati" },
		new Customer { ID = 12, FirstName = "Jayesh"   , LastName = "Patel" },
		new Customer { ID = 13, FirstName = "Nimesh"   , LastName = "Mishra" } ,
		new Customer { ID = 14, FirstName = "Shiva"    , LastName = "Reddy" } ,
		new Customer { ID = 15, FirstName = "Jasmin"   , LastName = "Malviya" }
		new Customer { ID = 16, FirstName = "Haresh"   , LastName = "Bhanderi" },
		new Customer { ID = 17, FirstName = "Ankit"    , LastName = "Ramani" },
		new Customer { ID = 18, FirstName = "Sanket"   , LastName = "Shah" } ,
		new Customer { ID = 19, FirstName = "Amit"     , LastName = "Shah" } ,
		new Customer { ID = 20, FirstName = "Nilesh"   , LastName = "Soni" }       };

	var results = from c in customers.AsParallel()
		      where c.FirstName.StartsWith("San")
		      select c;

With the simple addition of the AsParallel() extension method, the .NET runtime will automatically parallelize the operation across multiple cores. In fact, PLINQ will take full responsibility for partitioning your data into multiple chunks that can be processed in parallel.

PLINQ partitioning is out of the scope for this article, but if you’re curious about the inner workings of it, this blog post from Microsoft’s own Parallel Programming team does a great job of explaining the details.

When you will run the above sample queries , you might get same output but possibly in different order. Here Sample code 1 is an example of Sequential LINQ execution, while Sample code 2 is an example of Parallel LINQ execution.

Limitations

  1. PLINQ only works against local collections. This means that if you’re using LINQ providers over remote data, such as LINQ to SQL or ADO.NET Entity Framework, then you’re out of luck for this version.
  2. Since PLINQ chunks the collection into multiple partitions and executes them in parallel, the results that you would get from a PLINQ query may not be in the same order as the results that you would get from a serially executed LINQ query.

However, you can work around this by introducing the AsOrdered() method into your query, which will force a specific ordering into your results. Keep in mind, however, that the AsOrdered() method does incur a performance hit for large collections, which can erase many of the performance gains of parallelizing your query in the first place.

Sample code 3 : Preserving the Order of PLINQ Query Results Using the AsOrdered Method


	var results = from c in customers.AsParallel().AsOrdered()
		      where c.FirstName.StartsWith("San")
		      select c;

Controlling Parallelism

1) Forcing Parallel Execution :

In some cases, PLINQ may decide that your query is better dealt with sequentially. You can control this by using the WithExecutionMode extension method, which is applied to the ParallelQuery type. The WithExecutionMode method takes a value from the ParallelExecutionMode enumeration. There are two such values: the default (let PLINQ decide what to do) and ForceParallelism (use PLINQ even if the overhead of parallel execution is likely to outweigh the benefits).

Here is sample code which demonstrates the use of this method :


	var results = from c in customers.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism)
		      where c.FirstName.StartsWith("San")
		      select c;

2) Limiting the Degree of Parallelism :

You can request that PLINQ limit the number of partitions that are processed simultaneously using the WithDegreeofParallelism extension method, which operates on the ParallelQuery type. This method takes an int argument that states the maximum number of partitions that should be processed at once; this is known as the degree of parallelism. Setting the degree of parallelism doesn’t force PLINQ to use that many. It just sets an upper limit. PLINQ may decide to use fewer than you have specified or, if you have not used the WithExecutionMode method, may decide to execute the query sequentially.

Here is sample code which demonstrates the use of this method :


	var results = from c in customers.AsParallel().WithDegreeOfParallelism(2)
		      where c.FirstName.StartsWith("San")
		      select c;

3) Generating and Using a Parallel Sequence :


	IEnumerable<int> evens
		= ((ParallelQuery<int>) ParallelEnumerable.Range(0, 50000))
			.Where(i => i % 2 == 0)
			.Select(i => i);

Above code uses the Range method to create a sequence of 50,000 integers starting with the zero. The first argument to the method is the start index; the second is the number of values you require. Notice that we have cast the result from the Range method to a ParallelQuery. If we don’t do this, LINQ doesn’t recognize the sequence as supporting parallel execution and will execute the query sequentially.

4) Generating and Using a Repeating Sequence :


	int sum = ParallelEnumerable.Repeat(1, 50000)
			.Select(i => i)
			.Sum();

The static Repeat method takes an object and a count and creates a sequence where the object is repeated the specified number of times.

That’s all

Thats all for this article, I have tried to cover all important topic related to PLINQ. I hope this article will help you to start with PLINQ and gain some knowledge from it.

Hope this will helps !!!

Jay Ganesh

Reference links :

  • MSDN – Parallel LINQ – link
  • Difference between plinq and linq – link

Shout it

LINQ to SQL vs. ADO.NET Entity Framework

Hi all, recently I was surfing MSDN forum & reading discussion on “Linq to SQL vs ADO.NET Entity Framework“.

There I have found very good conversations between Michael Pizzo and Kavin Hoffman on the above given topic, so I feel why not share this information to my readers also.

Here is the query by Kavin Hoffman :

I know this has been asked before, but the answers I’ve read still haven’t cleared it up for me. People are asking me why they should wait around for an updated to ADO.NET Entity Framework (not currently linked to the Orcas builds) or if they should use LINQ to SQL, which _is_ part of Orcas.

Can someone clarify, hopefully in a way that can be repeated to others, what exactly the benefit of LINQ to SQL is over the EF and the other way around? I am hoping that there is little overlap between the purposes of these solutions and that there is a clear list of situations in which it makes more sense to use one over the other.

Here is the reply by Michael Pizzo :

LINQ to SQL and the Entity Framework have a lot in common, but each have features targeting different scenarios in the Orcas timeframe.

LINQ to SQL has features targeting “Rapid Development” against a Microsoft SQL Server database. Think of LINQ to SQL as allowing you to have a strongly-typed view of your existing database schema. LINQ to SQL supports a direct, 1:1 mapping of your existing database schema to classes; a single table can be mapped to a single inheritance hierarchy (i.e. , a table can contain persons, customers, and employees) and foreign keys can be exposed as strongly-typed relationships.  You can build LINQ queries over tables/views/table valued functions and return results as strongly typed objects, and call stored procedures that return strongly typed results through strongly typed methods.

A key design principle of LINQ to SQL is that it “just work” for the common cases; so, for example, if you access a collection of orders through the Orders property of a customer, and that customer’s orders have not previously been retrieved, LINQ to SQL will automatically get them for you.

LINQ to SQL relies on convention, for example default insert, update, and delete logic through generated DML can be overwritten by exposing appropriately named methods (for example, “InsertCustomer“, “UpdateCustomer“, “DeleteCustomer“).  These methods may invoke stored procedures or perform other logic in order to process changes.

The Entity Framework has features targeting “Enterprise Scenarios“.  In an enterprise, the database is typically controlled by a DBA, the schema is generally optimized for storage considerations (performance, consistency, partitioning) rather than exposing a good application model, and may change over time as usage data and usage patterns evolve.  With this in mind, the Entity Framework is designed around exposing an application-oriented data model that is loosely coupled, and may differ significantly, from your existing database schema.  For example, you can map a single class (or “entity”) to multiple tables/views, or map multiple classes to the same table/view. You can map an inheritance hierarchy to a single table/view (as
in LINQ to SQL) or to multiple tables/views (for example, persons, customers, and employees could each be separate tables, where customers and employees contain only the additional columns not present in persons, or repeat the columns from the persons table).  You can group properties into complex (or “composite”) types (for example, a Customer type may have an “Address” property that is an Address type with Street, City, Region, Country and Postal code properties).

The Entity Framework lets you optionally represent many:many relationships directly, without representing the join table as an entity in your data model, and has a new feature called “Defining Query” that lets you expose any native query against the store as a “table” that can be mapped just as any other table (except that updates must be performed through stored procedures).  This flexible mapping, including the option to use stored procedures to process changes, is specified declaratively in order to account for the schema of the database evolving over time without having to recompile the application.

The Entity Framework includes LINQ to Entities which exposes many of the same features as LINQ to SQL over your conceptual application data model; you can build queries in LINQ (or in “Entity SQL”, a canonical version of SQL extended to support concepts like strong typing, polymorphism, relationship navigation and complex types), return results as strongly typed CLR objects, execute stored procedures or table valued functions through strongly-typed methods, and process changes by calling a single save method.

However, the Entity Framework is more than LINQ to Entities; it includes a “Storage Layer” that lets you use the same conceptual application model through low-level ADO.NET Data Provider interfaces using Entity SQL, and efficiently stream results as possibly hierarchical/polymorphic DataReaders, saving the overhead of materializing objects for read-only scenarios where there is no additional business logic.

The Entity Framework works with Microsoft SQL Server and 3rd party databases through extended ADO.NET Data Providers, providing a common query language against different relational databases through either LINQ to Entities or Entity SQL.

So while there is a lot of overlap, LINQ to SQL is targeted more toward rapidly developing applications against your existing Microsoft SQL Server schema, while the Entity Framework provides object- and storage-layer access to Microsoft SQL Server and 3rd party databases through a loosely coupled, flexible mapping to existing relational schema.

I know this is a confusing area, and we’re trying to figure out how best to describe these differences to help customers make the appropriate choices.  Please let me know if this helps, or if there are still areas of confusion…

Thanks,
Michael Pizzo
Principal Architect
Microsoft Data Programmability

I hope this is good enough to differenciate LINQ to SQL and ADO.NET Entity Framework.

Jay Ganesh

Reference :

Shout it
kick it on DotNetKicks.com

SQL Cache Dependency with SQL Server, LINQ and ASP.NET 3.5

The following article demonstrates how to use SQL Cache Dependency with SQL Server 2005/2008, ASP.NET 3.5 and Extension Methods.

ASP.NET has several different varieties of caching features. This article will shine a light on a little known feature of ASP.NET 3.5 called SQL Cache Dependency. SQL Cache Dependency has been around since SQL Server 2000, but back then ASP.NET was limited as far as it had a polling mechanism built in so it would continually poll the database for changes, and when a change was found, it was up to the developer to notify the website that a change had occurred and make the necessary changes in the cache.

With the release of SQL Server 2005 and 2008, ASP.NET has a more mature way to perform SQL Cache Dependency.  The developer can now tell SQL Server to push notifications when data has changed. The biggest factor here is that the website does not have to continually poll the database.

Read more

Hope this will help

Jay Ganesh

Lazy Loading

Introduction

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program’s operation if properly and appropriately used. The opposite of lazy loading is Eager Loading.

Article – 1: jQuery Tabs and Lazy Loading by Malcolm Sheridan

In this article I will connect to the Northwind database using LINQ to SQL, and display customer and product information in separate tabs. I’ll also show you one way of lazy loading these tabs so the data is retrieved only once, not each time a tab is selected.

Read more

Article – 2: Lazy Loading jQuery Tabs with ASP.NET by Mikesdotnetting

This article looks at efficient use of jQuery tabs when displaying data. Specifically, it covers how to lazy-load data, so that it is only accessed and displayed if the tab is clicked.

Lazy Loading is a well-known design pattern that is intended to prevent redundant processing within your application. In the case of tabbed data, there seems little point retrieving and binding data that appears in a tabbed area that no one looks at. So, this examples covers how to defer data access and display until the user wants it – which is defined by them clicking the relevant tab.

Read more

Article – 3: Eager Loading and Lazy Loading in ADO.NET Data Services by Gil Fink

The default behavior of a data service’s .NET client is not to load the entities’ associated objects. When we request an entity we will get it from the service but its associated objects will not load up at all.

Lets say that I have two entities in my program

  • a course
  • a department

The associations between the entities are that a department can have a lot of courses and a course belongs to one department.

When I load a department it’s list of courses will be empty. trying to iterate the list of courses will give nothing because the courses will not load until we tell them to be loaded explicitly.

This is done by the LoadProperty method of the data service context.

Read more

 

I have a great learning experience thru this.

Now its your turn to have it.

kick it on DotNetKicks.com
Shout it