Code First

EF 4.1 Quick Tip: Add/Attach Returns Your Entity

We did a few things in EF 4.1 that were not at all ground-breaking or cool or anything like that, but were intended only to make programming a little bit more pleasant. One of those was making the Add and Attach methods return a reference to the added or attached entity.

This is nice because it can sometimes save a local variable or a line or two of code and thereby make your code easier to read.  For example, in a little test app I was just working on I wanted to create a new “Doc” entity, add it to the context, then use it later in the same method.  Instead of writing:

var doc = new Doc();

I was able to write this:

var doc = context.Docs.Add(new Doc());

Another advantage of returning the added entity is that it allows the Add/Attach methods to be more composeable. For example, later in the same method I had some code that attempted to find an entity in the context and, if the entity was not found, created a new one and added that new entity to the context. Instead of writing:

var word = context.ChangeTracker.Entries<Word>()
                                .Select(e => e.Entity)
                                .SingleOrDefault(w => w.TheWord == theWord);
if (word == null)
    word = new Word { TheWord = theWord };

I was able to use a more functional approach:

var word = context.ChangeTracker.Entries<Word>()
                                .Select(e => e.Entity)
                                .SingleOrDefault(w => w.TheWord == theWord)
    ?? context.Words.Add(new Word { TheWord = theWord });

Hopefully once in a while you can use the return value from Add or Attach and be just a little bit happier because of it. :-)

Thanks for reading!


4 replies »

  1. Hey Arthur, nice post! I will definitely use this.

    Do you know if EF will support SQL Azure retry logic any time soon? It’s a real pain to have to wrap every query with the SQL Azure retry logic (see this post:

    It seems to me, if we could just add a “IsSqlAzure=true” to the connection string, and have EF take care of the rest, it would be great!!!


    • @Matt I know a couple of people have been looking into this but I’m not sure where things have landed. I’ll try to get some more info for you next week.


      • Thanks Arthur. Any help here is much appreciated! If it helps, the article I linked to has this at the bottom:

        Authored By: James Podgorski
        Review By: Valery Mizonov, Mark Simms, Faisal Mohamood

      • @Matt The SQLClient team recently released an update that fixes the connection pooling issue–see this . There isn’t currently any code being added to EF to do automatic retries at the EF level. More work may be done on this in the future.