Sunday, November 15, 2009

LINQ and Entity Framework Posts for 10/26/2009+

Note: This post is updated weekly or more frequently, depending on the availability of new articles.

Entity Framework and Entity Data Model (EF/EDM)

Julie Lerman offers An Improved Entity Framework Tip for EF4 thanks to Zeeshan on 11/13/2009:

In my EF Tips & Tricks talk that I just did at DevConnections, I have a suggestion to reduce redundant methods where you might expose queries to generate reference lists. …

Instead I have a single generic method, GetRefernenceList<TEntity> that uses some tricks with Entity SQL and MetadataWorkspace  to dynamically build the query and return the requested list.

This is still the right way to do it in VS2008. However, Zeeshan Hirani suggested to me that with EF4, there’s a better way – the new CreateObjectSet method.

This let’s me pass in the entity type and create a queryable set.

Alex James continues his EF Tip series with Tip 43 – How to authenticate against a Data Service of 11/13/2009 by describing the problem:

When writing code against a Data Service, like say SharePoint, the client application must provide a valid set of credentials, or you will see a dreaded “401 Unathorized” response.

For Silverlight applications hosted on the same site as the DataService, this is generally handled for you automatically.

But WPF applications, for example, need manual intervension.

Thankfully, he also describes the solution, which is “to set the Credentials property on your DataServiceContext before you issue any queries or updates.”

Alex also points out an Interesting series of Posts exploring Code-Only posts by Alan Wertheim “about using Code-Only to write clean code.”

Danny SimmonsAttachAsModified revisited post of 11/9/2009 describes how the ObjectStateManager.ChangeObjectState method has reduced the complexity of setting an entity’s properties state to modified:

It seems like on a fairly regular basis these days I encounter a question or an issue about the EF to which the answer is “I know I wrote a blog post about that…”  Then when I go search my blog and find the post I discover that the post was written before EF4 and things are now a lot easier than they used to be.  Here’s another one of those situations:

About a year ago I wrote a post presenting a little extension method AttachAsModified which was designed to make a few small n-tier scenarios easier to write by hand.  You can read the post for more background on the situation, but the issue which came up today is that in EF4 the code in that post can be made much simpler.  The hardest part of the code before was iterating over an object’s properties and telling the ObjectStateManager to mark each property as modified.  It wasn’t all that many lines of code, but it was pretty obtuse.  The reason for this code is that the ObjectStateManager had two relevant methods—one marks the whole entity as modified but not any of its properties, and the other marks a single property as modified.  What was missing was something that would set all of the properties to modified, and the trick for that was to use metadata from the EF to get the list of persisted property names.

As part of our effort to improve n-tier support in general for EF4, though, we added the method ChangeObjectState to ObjectStateManager, and if you use that method to change an object’s state to “Modified”, then it will do the work of mark each property as modified for you.  So my AttachAsModified method becomes trivial—just one call to attach the entity and another call to change its state. …

Alex JamesTip 42 – How to create a dynamic model using Code-Only of 11/9/2009 explains how to overcome lack of a strongly typed Context class:

What if you make a determination at runtime that you need a model, there isn't an appropriate strongly typed Context class lying around.

and explains:

It turns out you can use ObjectContext directly. When you do this though Code-Only knows nothing about the model. But that isn’t that bad all you need to do is explicitly tell Code-Only about all the things it would normally learn from the strongly typed context.

He concludes with an “end-to-end” code sample.

His Tip 41 – How to execute T-SQL directly against the database of 11/7/2009 notes:

Sometimes you’ll find you need to issue a query or command that the Entity Framework can’t support. In fact this problem is common to most ORMs, which is why so many of them have a backdoor to the database.

The Entity Framework has a backdoor too …

and delivers Tip 40 – How to materialize presentation models via L2E on the same day.

Julie Lerman discusses MSDN Guidance on ASP.NET MVC vs WebForms and its Impact on my EF + ASP.NET Work in this 11/7/2009 post:

Last year at the fall 2008 DevConnections conference, I was very happy to hear Scott Guthrie providing a clear message about web forms vs. MVC in ASP.NET 4.0.

Now, I am seeing something that is new for MSDN Documentation, not only similar clarity but actual guidance on when Microsoft suggests to use one over the other.

You’ll find this in two places.

First, in the ASP.NET MVC Overview topic. In this document, their is a list of advantages of MVC and a list of advantages of web forms apps.

Next, in the topic titled Compatibility of ASP.NET Web Forms and ASP.NET MVC, there is a short list of strengths of web forms and another of the strengths of MVC. Following this are short lists of features that are compatible with MVC and then those that are incompatible with MVC. …

Danny Simmons says It’s time to rip up EntityBag and throw it away in this 11/5/2009 post:

A couple of years ago when the overall shape of what we would ship in the first release of the entity framework became apparent, I realized that one of the biggest issues users of that release would fight with was creating N-tier applications.  So I started a project to explore the space by creating something I called EntityBag.  In spite of the fact that I wasn’t too thrilled with the overall approach, I thought it would be a good exercise and if nothing else it would help illuminate the issues with building this kind of application on the EF and demonstrate to folks what techniques they could use with the EF to solve these problems.  The result of this investigation was a series of blog posts and a sample project which I uploaded to code gallery.  You can check out the project at:  That site also has links to each of the relevant blog posts which is where the real interesting data lives.

At the time that I created EntityBag (mostly January 2008), the version of the Entity Framework was called “beta 3”, and it was before the first RTM of the product.  Unfortunately, when the first version was finally released we included a change to by default generate classes which would serialize an entire graph of related entities as one (at beta 3 only one entity would serialize at a time) which ended up breaking EntityBag and the fix involved fairly major surgery.  From the beginning this project had never been intended as a full-quality production solution—I just wanted to teach people how they could use the EF to build the right solutions for their particular projects.  In addition I wanted to work with the team to produce a much better, long-term solution for N-tier apps, so whatever time I had available for this topic I poured into the next release of the EF (EF4) rather than into updating the EntityBag project.

and then goes on to describe the new features in EF Feature CTP 2 that make coding n-tier EF projects simpler. Danny also provides the following links to related articles:

  1. Entity Framework: Anti-Patterns To Avoid In N-Tier Applications
  2. Entity Framework: N-Tier Application Patterns
  3. N-Tier Apps and the Entity Framework: Building N-Tier Apps with EF4

So, death to EntityBag!  Long live EF4!

Julie Lerman analyzes New Entity Framework Feature CTP for VS2010 Beta 2 in this 11/5/2009 post:

The EF team just released the newest version of the Feature CTP that is now compatible with VS2010 Beta2. Hooray for compatibility, but more importantly, we can now work with a greatly enhanced version of the Code Only feature and Self-Tracking Entities. Code-Only is the API that allows you to use EF without a model at all. Self-Tracking Entities provides tracking for entities across WCF Services and their clients .

I’ll talk a bit about Code Only here, which will be of great interest to Domain Driven  Developers.

Matthieu Mezil’s ADO.NET Data Services Client context post of 11/4/2009 begins:

One of the great points with EF is the eco-system around it. Even if it can be used without EF, I think that ADO .NET Data Services is one of the technologies in this eco-system. Indeed, using ADO.NET Data Services with EF implies almost no code to write some LINQ queries in the client tier or to save the changes.

However, when we use the generated proxy in the client tier there are some bad points.

Matthieu continues with an elucidation of the “bad points,” which he fixes with a T4 template.

Julie Lerman explains Designer Support for One-Way navigations in Entity Framework 4 on 10/29/2009:

In EF v1, it is possible to have one way navigations where you have an association between two entities but a navigation in only one of them. But the designer didn’t support this. If you deleted a navigation, the association was automatically removed.

You could, however, go into the XML and remove the navigation property manually, leaving the association, association mappings and the partner navigation property in tact.

The new designer now supports one way relationships – both for models with foreign keys and models without foreign keys.

Here is a model that does not use foreign keys. The associations, by the way, are called “independent associations” when there is no foreign key involved.

Matthieu Mezil shows you how to Generate a WCF service from an edmx with T4 v2 in this 10/26/2009 article:

I recently published a T4 template to generate a WCF service. I updated it to be able to load its relationships from an entity.

When the template is written (what I’ve already done), it generates the WCF service for us (you just have to set the end point in the config file).

As I explained in my previous post, the great point with it is the fact that the code writing time is not dependant of the number of entities on the model. Moreover,  the template is generally (it’s the case here) not dependant of the model so we can use it with another model and more generally with another project.

See Julie Lerman discusses Self-Contained Entity Framework Models and ASP.NET Dynamic Data in the “ASP.NET Dynamic Data (DD) section.


Ayende Rahien’s Some observations on Linq to Sql & Entity Framework codebases post of 11/25/2009 observes:

So, I have to do a lot of L2S and EF work recently, while trying to create L2SProf and EFProf. The interesting tidbit is that I got a totally different approach to using them than almost anyone else.

I don’t really care for either as an OR/M (I have my own, thank you very much), I only care for plugging into them deeply enough that I can get the information that I want.

With L2S, that was fairly easy, all I needed to do was figure out how to get access to the logging that it was already doing, and I was pretty much done. With EF, there isn’t any logging, and I was left having to write my own EF provider (and then plugging that in). I am going to talk about how I plugged myself into EF at some length some other time.

Ayende reports Linq to Sql Profiler is now on public beta on 11/13/2009:

Well, after talking about it quite often recently, I think it is just about time to make this public.

The Linq to Sql Profiler is now on public beta, and it is even more awesome than you could imagine.

We are able to get a tremendous amount of information out of Linq to Sql, so from profiling behavior it is quite on par with NH Prof or Hibernate Profiler.

Here is a screen shot:


Please note that the UI color scheme is still under development, we would love to hear feedback about that as well.

Like NH Prof, L2S Prof is currently offered in a 30% discount for the duration of the beta period.

LINQ to Objects, LINQ to XML, et al.

Jim Wooley’s  LINQ tools [i]n the Toolshed post of 11/5/2009 reports:

This summer at the Jacksonville Code Camp, I had the pleasure of being part of the taping of Russ' Fustino’s Toolshed. Finally, the episode has  been posted on Channel9 for you to enjoy. Here’s the overview of the episode: Toolshed: Episode 5 - Its All About The Tools TV Show

Episode 5 has killer content on Deep Zoom, Expression Web 3, a codeplex project on a Snippet Editor for Visual Studio, LINQ Tool Samples, LINQ Pad, Link To Twitter, Expression Blend 3 Importing Adobe assets, and an incredible codeplex project must see on a solid Silverlight website starter kit using best practices!  This is Russ's Tool Shed's best effort yet! Grab a beer and hope you enjoy this most educational, enlightening and entertaining instant classic video!

The LINQ Tools segment starts at 44:35 if you want to jump ahead.

ADO.NET Data Services (Astoria)

The ADO.NET Team Blog’s Updated Feature CTP Walkthrough: Code Only for Entity Framework of 11/12/2009:

[C]overs Code Only improvements in the CTP2 release for VS 2010 Beta2. This walkthrough shows how you can change the default model like specifying property facets and navigation property inverses as well change the default mapping by changing the default inheritance strategy and table and column names. You can learn more about the CTP2 Code-Only improvements from our blog post on the EFDesign blog.

Code Only ships as part of the Microsoft Entity Framework Feature CTP 2. The CTP works on top of the latest version of the Entity Framework released as part of .NET 4.0 Beta 2.


  1. This walkthrough requires Visual Studio 2010 Beta 2
  2. The Microsoft Entity Framework Feature CTP2, that can be downloaded from here.
  3. A local SQL Server 2008 Express instance has to be installed as SQLEXPRESS.
  4. Download and extract the initial solution attached to this post. …

and its Automatic Generation of Stored Procedure Return Types post of the same day describes:

A new feature of the Entity Framework in .NET 4.0 is the ability to return collections of complex type instances from stored procedures. In the next public release of the designer, we have enriched this functionality by adding the ability to automatically create these complex types by querying stored procedure metadata from the database server. To demonstrate this feature, we will use the Northwind database, and we will focus on a stored procedure called “CustOrdersDetail”.

The Foreign Key Relationships in the Entity Framework post of 11/6/2009 begins:

Last March Alex James posted to our design blog about our plans for adding foreign keys to the entity framework. Since then we’ve pushed forward with implementing FK associations and properties and have included them in Visual Studio 2010 Beta 2. This article offers a walkthrough of foreign key relationships in the EF and how they’re useful in VS2010 Beta2. For more information, the documentation and a number of blogs offer useful background about the logic behind adding EF foreign key relationships; here are a few links:

Defining and Managing Relationship MSDN documentation

and continues with a detailed walkthough.

Model First with the Entity Framework 4 of 11/5/2009 demonstrates new designer features in Visual Studio 2010 Beta 2:

In a previous post, we walked through the designer’s “out of the box” database schema generation experience. In this post, we show how some new designer features in VS2010 Beta 2 integrate with this capability, then we pop the hood and show how easy it is to replace or extend parts of the generation system.

We will begin with a simple model that contains two newly supported constructs: Employee.EmployerId is a foreign key that references Company.Id, and Person.Address is a complex type.


ADO.Net Entity Framework Community Technology Preview Released! celebrates on 11/4/2009:

We’ve released an update of the Entity Framework Feature CTP!  The updated CTP includes many requested improvements and added features we’ve gathered from the community since the release of our first CTP and supports installation with Visual Studio 2010 Beta 2 as well.  Some of the improvements and added features added since the last CTP include:

    • Enhancements to Code Only, including-
      • Fine Grained Control over model
        • Specify Navigation Property Inverses
        • Specify Property Facets
        • Complex Types
      • Customizable Mappings
        • Change Table Name, Column Names
        • Specify Custom Inheritance Strategy
        • Entity Splitting
        • Join Table Mapping
    • The Self-Tracking Entities template, allowing code generation of EF entities that facilitate ease of use in WCF/N-Tier scenarios-
      • Foreign Key associations: Self-Tracking Entities can take advantage of the Foreign Keys in the Model feature added in .NET 4.0 Beta 2 and can contain both navigation properties and Foreign Key properties for the same association. Fix-up logic has been tidied up to be aware of FKs.
      • Support for Silverlight 3: Generated entity types can be compiled to target Silverlight 3 and can be used in combination with Silverlight-enabled WCF services.
      • Databinding support: Generated entity types now implement INotifyPropertyChanged and use ObservableCollections allowing them to work better with WPF and Silverlight databinding.
      • Richer concurrency control support: Self-Tracking Entities now support the same variations for optimistic concurrency control as the Entity Framework. Original values are preserved for all required properties according to their concurrency mode in the Entity Data Model.
      • Improved independent association support: The approach for managing entities with dangling references has been reengineered to avoid unnecessary database round-trips.
      • New and improved methods: AcceptChanges, StartTracking, StopTracking where added and the existing MarkAsX methods are now extension methods.
      • Generated code improvements and refactoring: The ApplyChanges implementation has been moved to the Context template so the template has no binary dependencies besides Entity Framework. Generated code for entity types have been refactored.

The Astoria Team’s Enabling X-Domain access to your Data Services post of 11/5/2009 explains:

In the Astoria V1.5 CTP2 release, we introduced support for X-Domain and Out Of Browser access to Data Services in our Silverlight client library.

This blog post talks about how to enable Cross-Domain access to Data Services from the Silverlight client library. …

and its Using Data Services over SharePoint 2010 – Part 2 – CRUD post of 10/29/2009 begins:

In part 1 you learned how to get SharePoint 2010 and Astoria working together, how to add a Service Reference to your Client Application and how to do a basic insert.

In this installment you will see full CRUD, so you’ll learn how to do queries, data binding, updates and deletes. …

ASP.NET Dynamic Data (DD)

Julie Lerman discusses Self-Contained Entity Framework Models and ASP.NET Dynamic Data in this 11/15/2009 post:

In an earlier post, I wrote about the new awesomeness that ASP.NET 4.0’s Dynamic Data brings to many to many relationships.

I frequently notice that most DD demos demonstrate creating the data model within the same project as the DD website.

Even though a typical Dynamic Data app is for RAD development and isn’t focused on application architecture (come on, the data access is buried in the UI), I still can’t bare to store my model inside of the UI project. All of my EF Entity Data Model’s are housed in their own projects.

This is not a problem at all for a Dynamic Data site. Like any other project that leverages an EDM in a separate project, you only need to perform three steps to point to the external model:

  1. Add a reference to the project that contains the data model
  2. Add a reference to System.Data.Entity.dll
  3. If it’s the executing app (in this case it is), provide the EntityConnection string, most typically by adding it into the web.config file

For Dynamic Data, there is one additional consideration that I was torn over.

I have my model in it’s own project because I like to be able to reuse it in other applications. …

Julie Lermon discusses ASP.NET 4.0 Dynamic Data and Many to Many Entity Framework Entities on 11/7/2009:

Even though I’m a much bigger fan of distributed apps than using UI bound data binding, it’s still important for me to know how these various tools work – especially since I need to write about them in my updated E.F. book. ;)

I did not play much with Dynamic Data controls in VS2008 and just made a cool discovery in VS2010 Beta 2. This may not even be new, but as I’m sitting 30,000+ feet over the Atlantic ocean, I don’t have access to VS2008 at the moment to check.

She was “surprised when [she] chose to Edit the person and saw how brilliantly the Dynamic Data templates handled the Entity Data Model’s many to many relationship.”

Steve Naughton’s Conditional UIHint post of 10/30/2009 begins:

Long time no posts but I’m posting again should have some DDv2 and ASP.Net 4.0 samples soon.

I just had need of a conditional UIHint for a project I was working. …

and provides listings for the required code.

blog comments powered by Disqus