All posts by Julie

What do you want to see in Entity Framework?

A friendly reminder about the UserVoice site where you can suggest and vote on features you’d like to see in Entity Framework (http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions) or in WCF Data Services (http://data.uservoice.com).

The EF team is wrapping up work on changes to the core EF APIs that will be part of the .NET 4.5 release. We’ve had access to the preview of these new features since June 2011. Here’s an MSDN Magazine article reviewing some of the most prominent features that you’ll find in there: http://msdn.microsoft.com/en-us/magazine/hh394151.aspx.

But EF continues to evolve. The team pays close attention to the suggestions developers make (and vote on) on user voice. In fact, it’s a bit of a popularity contest. If one feature suggestion has hundreds of votes, it will get a lot more attention from the team than a suggestion with only 10 votes.

Here’s a look at hot suggestions.

Top 10 Suggestions Overall

Improved SQL Generation (status=Started) 1204 votes

Batch CUD support (status=Under Review) 981 votes

EF Support for Second Level Cache (status=Under Review) 535 votes

Entity Designer: Speed up & Optimize for using with ~200+ entities 453 votes

Support for multiple databases (status=Under Review) 441 votes

Designer Support GUID as Entity Key  429 votes

Schema Migration a la Rails Migrations (status =Started (Code First Migrations)) 406 votes

TPT (Table-Per-Type) Inheritance Performance (coming in .NET 4.5) 369 votes

Allow filtering for Include extension method (status=Under Review) 319 votes

Allow default date = NOW and provider.MinDate in CSDL (my suggestion Smile) 216 votes
(this isn’t as much of a problem now with code first, but for EDMX it’s still an issue)

There are currently 276 overall. Some have been completed. Some may be duplicates. But if there are features you care about getting into EF, take a look at the list and vote and *promote* the ones you care about.

Vermont IT Jobs: SysAdmin at NRG Systems in Hinesburg (a cool company…c’mon do it!)

clip_image002

http://www.nrgsystems.com/
Hinesburg, Vermont

Desktop/Systems Administrator

Job Description

Key Focus

The Desktop/Systems Administrator is responsible for providing first line support to NRG’s information technology users; assuring that user’s IT resources are performing as required. This individual helps users achieve their goals by providing excellent customer service for IT issues/requests, while at the same time assuring the integrity and security of NRG’s information resources.

The Desktop/Systems Administrator will report to the Information Technology Manager and will work with the information technology team to achieve the objectives of the department that are aligned with the company strategic goals.

Primary Responsibilities

  • Manage NRG’s IT Help Desk ticket system by monitoring ticket submission, resolving tickets that fall within the Desktop Administrator job responsibilities, and assigning other tickets to appropriate individuals within the IT department.
  • Resolve user requests for problem resolution regarding desktop hardware, printers and other peripherals, e-mail, MS Office applications and other supported desktop applications, internet/intranet access, in a timely and professional manner.
  • Coordinate the procurement, provisioning, and management of new desktop/laptop computers, printers, A/V equipment, and desktop application licenses to support current and new users.
  • Assure that NRG’s spam, virus, and malware protection is functioning at optimal level.
  • Manage user accounts and provide IT orientation to new employees.
  • Monitor server backup performance, assure proper backup tape storage and rotation, and identify issues that require resolution.
  • Purchase and install new versions of desktop software to maintain currency.
  • Utilize VMWare Virtual Center to support the Network Administrator in managing and maintaining the server and network environment.

Qualifications

  • 4-year degree in computer science, software engineering, or related field
  • 3+ years IT experience with hardware and software support
  • Exceptional communication and teamwork skills.
  • Excellent analytical and problem resolution skills.
  • Excellent organizational skills.
  • Ability to work independently, and prioritize multiple tasks
  • Demonstrated knowledge of desktop/laptop hardware repair for common issues such as hard drive replacement, memory replacement, etc
  • Demonstrated knowledge of Windows XP, Windows 7, Windows Server, VMWare Virtual Center, SQL Server, Active Directory, IIS, Linux.
  • Microsoft certifications a plus
  • Experience in a manufacturing environment a plus

Oracle Releases Provider with EF 4 Support (but not really EF 4.1 and EF4.2)

Oracle has finally released it’s version of ODP.NET that supports Entity Framework for use in production environments.

This is great news for many developers! 

And they report that this release supports EF 4.1 and EF 4.2. That should mean Code First and DbContext but thanks to Frans Bouma sending me the limitations doc (that is part of the installation ) we can see that they aren’t! Too bad.

7. ODP.NET 11.2.0.3 does not support Code First nor the DbContext APIs.

So, that means “not really EF 4.1 and EF 4.2 support” in my opinion. But they told us already that Code First & DbContext weren’t going to make it in. So it was just the momentary surprise of misunderstanding their meaning about EF4.1 & 4.2 support that deflated me a bit. 😉

Howver…I imagine Code First and DbContext are still leading edge for the types of big corporations that use Oracle. The core EF 4 support is a big deal.

I’ll follow up with Oracle for clarification.

More from Oracle (including downloads) here: http://www.oracle.com/technetwork/topics/dotnet/whatsnew/index.html

Note: They’ve updated the what’s new page to say "Code First is not supported." That’s helpful. Be sure that even thought it’s not mentioned there, EF 4.1/4.2 DbContext API is not supported either.

EMail Q&A: What about Entity SQL and why direct DB access?

I received this pair of questions about EF in email and thought I would share the questions and my reply.

Q:

I’ve read some articles about Code First, I’ve tried to do some samples and I’m going to read you last book.

I’m surprised about 2 issues. The first is that it’s possible to write native SQL code (with context.Database.ExecuteSqlCommand and context.Database.SqlQuery methods) and the second is that I’ve not been able to use EntitySQL or Query Builder Methods.

Now, the idea of EF was create a model, operate with objects and use a common language (EntitSql) to interact with "some" databases. But now? We are coming back? Yes, we can use Linq2Entities and SaveChanges but I don’t understand the philosophy of these opened doors upon the database.

I’m wrong?

What’s your idea?

My A:

Dbcontext doesn’t replace ObjectContext. It just makes it easier for devs to access the most common things.

You can still use ObjectContext. You can even use DbContext and access ObjectContext functions when you need to.

Entity SQL was created before the data team knew about LINQ. You can express most queries with LINQ and it works with any EF-compliant database provider, just as ESQL does.

The direct database access command features are a "backdoor" that devs asked for. It should be used only on rare occasions when you need to access something in the database that is not part of the model.

Use Projections and a Repository to Fake a Filtered Eager Load

Entity Framework’s Include method which eager loads related data in a query does not allow sorting and filtering. People ask for this feature frequently.

There is a way around the problem,  I wrote about it in  the June Data Points column in MSDN Magazine (Loading Related Data: http://msdn.microsoft.com/en-us/magazine/hh205756.aspx) but since I just saw another comment on twitter about this, I thought I would stop working on Chapter 7 of the DbContext book that is already delayed and write a quick blog post about using a projection instead.

One caveat…you cannot do this if you have a long running context and you want the objects to remain attached to the context. If there are other related entities in the context, the context will always give them to you. More on this at the end of the post.

Okay, today’s model will be based on a roads and trees on that road. I need some type of guide because we’ve been socked in with fog for two days and I can barely see the trees across my road.

We’ll have two classes (and no I’m not trying to rub in the fact that we don’t have geo support yet, but it’s coming in .NET 4.5.)

public class Tree
  {
    public int Id { get; set; }
    public string Description { get; set; }
    public decimal Lat { get; set; }
    public decimal Long { get; set; }
    public int RoadId { get; set; }
  }
  public class Road
  {
    public Road()
    {
      Trees = new List<Tree>();
    }
    public int Id { get; set; }
    public string Name { get; set; }
    public string Town { get; set; }
    public List<Tree> Trees { get; set; }
  }

The way loading works in Entity Framework is an all or nothing scenario with one exception.

The DbContext lets you do a filter in an explicit load (i.e. after the root is already in memory). Here’s a passing test which loads only maple trees and checks to see that the count of non-maple trees is NOT greater than 0.

(MyInitializer seeds the database with one road that has three related Trees (a maple, a maple and a pine)).

    [TestMethod()]
    public void CanFilterOnExplicitLoad()
    {
      Database.SetInitializer(new MyInitializer());
      var context = new DataAccess();
      var road = context.Roads.FirstOrDefault();
      context.Entry(road).Collection(r => r.Trees)
        .Query().Where(t => t.Description.Contains("Maple"))
        .Load();
      Assert.IsFalse(context.Trees.Local
.Where(t=>!t.Description.Contains("Maple"))
.Count()>0);
    }

But that’s beside the point, since the question is about eager loading.

You can’t filter when eager loading with Include.

But you can get the results you want eagerly if you project.

  [TestMethod()]
    public void CanFilterOnProjection()
    {
      Database.SetInitializer(new MyInitializer());
      var context = new DataAccess();
      var road = context.Roads
        .Select(r=>new{
          r,
          r.Trees.Where(t=>t.Description.Contains("Maple")})
        .FirstOrDefault();
      Assert.IsFalse(context.Trees.Local
.Where(t => !t.Description.Contains("Maple"))
.Count() > 0); } }

That’s nice but whine whine whine, I returned an anonymous type.

If you use a repository, you can hide that.

  public class DumbRepositoryButGoodEnoughForThisDemo
  {
    DataAccess _context=new DataAccess();

    public List<Road> GetRoadsWithFilteredTrees(string treeFilter)
    {
      var roadAndTrees = _context.Roads
       .Select(r=>new{
          Road=r,
          Trees=r.Trees.Where(t=>t.Description.Contains("Maple"))})
        .ToList();
      return roadAndTrees.Select(rAt=>rAt.Road).ToList();
    }
  }

When I return the list of roads from the projection, the Trees will be attached thanks to the context recognizing the relationships.

Here’s another test that does pass:

   [TestMethod()]
    public void RepositoryFilteredRoadsReturnsRoadWithTrees()
    {
      Database.SetInitializer(new MyInitializer());
      var rep = new DumbRepositoryButGoodEnoughForThisDemo();
      var roads = rep.GetRoadsWithFilteredTrees("Maple");
      Assert.IsTrue(roads.FirstOrDefault().Trees.Any());
      Assert.IsFalse(roads.FirstOrDefault()
.Trees
.Where(t => !t.Description.Contains("Maple"))
.Count() > 0); }

And a screenshot as further proof:

projection 

Scenario When This May Not Work As Expected

As Brian points out in the comments, there is one BIG draw back that is also a problem with the filtered explicit load. If there are already related entities tracked by the context, they will automatically be attached to any related entity in the context. That means if the Pine tree was already being tracked then as long as the Road is attached to the context, it will see ALL of the related trees in the context, including the Pine that was already there.

If you are using a pattern where you have a short-lived context that is instantiated just to execute the query, then it’s not a problem. Most of my architectures are like this. But if you are writing a Windows Form or WPF form and have a context that hangs around, you could run into this problem.

You’ll never avoid the problem when the entities are attached to the context.

But here’s a twist on the repository method that will return disconnected objects from a context that is managing multiple object.

   public List<Road> GetDisconnectedRoadsWithFilteredTrees(string treeFilter)
    {
      var roadAndTrees = _context.Roads.AsNoTracking()
       .Select(r => new
       {
         Road = r,
         Trees = r.Trees.Where(t => t.Description.Contains("Maple"))
       })
        .ToList();

      var rt = new List<Road>();
      foreach (var r in roadAndTrees)
      {
        r.Road.Trees.AddRange(r.Trees);
      }
      return roadAndTrees.Select(rAt => rAt.Road).ToList();
    }

Downloads for Code First book are online

The downloads samples are available for Programming Entity Framework: Code FIrst on the downloads page of the book’s website (learnentityframework.com).

Rowan and I are busy working on the next book (Programming Entity Framework:  DbContext API) right now. Hopefully it will go into production in the next week or two.

Here are links to get a copy of the book:

Programming Entity Framework 2nd edition
From OReilly.com: Ebook (PDF, .mobi, ebook) and print here
Amazon  –> Print  Print version     Kindle:  Kindle Version
Plenty of other sources as well

Programming Entity Framework: Code First
From OReilly.com: Ebook (PDF, .mobi, ebook) and print here
From Amazon: Kindle and print are available: direct link to Amazon page

Programming Entity Framework 2nd Edition vs Code First Edition

I’ve had tweets and emails from readers asking if there is any point to reading the 2nd edition of Programming Entity Framework if they are only planning to use Code First and DbContext.

(Before answering, I want to add a disclaimer that my response is not geared towards my desire to increase royalties in order to pay off my mortgage someday. That wouldn’t be possible unless I put Harry Potter or Steve Jobs names on the cover. Hey, now there’s an idea! Smile )

Yes, the 2nd edition is completely relevant although there are bits within there that will be irrelevant.


Getting your hands on the book(s):

2nd edition
You can get print & ebooks (PDF/mobi (for Kindle) etc) directly from the publisher here
Amazon  –> Print  Print version     Kindle:  Kindle Version  
Plenty of other sources as well

Code First
Ebook is available today (Nov 21, 2011) with print coming soon here
Kindle should be available by Wednesday (Nov 23, 2011) on Amazon.com with print coming shortly after that: direct link to Amazon page


To begin with, I suggest reading this blog post about the difference between what’s in Code First/DbContext and the core EF APIs that are part of .NET 4 (Code First and DbContext are now “The Entity Framework”).

The CF book (Programming Entity Framework: Code First edition) is a relatively short book (175 pp) that covers how Code First enables you to create an entity data model that Entity Framework can use directly from your domain classes. It explains how Code First works by convention and how to use the Data Annotations and Fluent API to configure the model when convention don’t interpret your classes as you intended. the book also goes into detail on how Code First “database initialization” feature works and how to control it. In one of the final chapters, we cover some advanced features of Code First.

That’s the entirety of the book. So what it’s doing is showing you how to achieve a model without the designer, replacing only a very small part of what you learn in the 900 page book (the part it replaces is how to achieve a model using the designer). Even in the 2nd edition chapters that cover advanced modeling, you learn more than just how to click here and type there in the designer. You get a thorough education on the effects. For example, you’ll learn how to build inheritance into your model in the designer, but then you’ll look at (or write if you want) code that uses this inheritance hierarchy and helps you understand how it works, the affect on your application and on your data. In the Code First book, you’ll learn how to achieve the same inheritance hierarchies using code first (convention, annotations and fluent) but we do not spend very much time on how this affects your applications.

The book that Rowan and I are writing right now will focus on the DbContext API including the new state management and Validation API. This will also be narrowly focused. DbContext gives you easier access to the most common coding patterns that are a little trickier to achieve with the underlying ObjectContext. A great example is that in Chapter 21 of 2nd edition, I have some extension methods to make it easier to get to tracked objects. DbContext now has the Local method so you won’t need those. The underlying behavior of EF does not change.

We were avoiding writing another book that might end up at 1200 pages (and take forever to write) were we to include all of the information in once place. Instead, the goal was to give you the specific information that was missing in as short and digestible a format as we could. The short books may be all you want. If you are interested in the deeper aspects of how EF works, how to control it, how to deal with exceptions, performance, transactions, application patterns etc etc, then you can learn those things in the 2nd edition.

When the DbContext book is finished, our plan is to put together a cook book of application DbContext for use with DbContext & Code First that are relevant to those you’ll find with ObjectContext and EDMX (POCOs & EntityObjects) in the 2nd edition.

I hope this will help you with your journey.

Programming Entity Framework: Code First edition is now available as an ebook!

OReilly Media pushed the ebook versions (PDF, mobi (for kindle) & others) of Programming Entity Framework Code First live this morning! You can get it at http://shop.oreilly.com/product/0636920022220.do. The print version should be available soon. Print is also available for pre-order on the OReilly site as well as on Amazon at http://juliel.me/ufZtlb. Amazon should have the kindle version available shortly. On twitter, Shawn Wildermuth said “I’ll get it when the Kindle version ships..tech books on a Kindle Fire are really good so far”.