views:

55

answers:

1

Using Entity framework v4, and the POCO entity generator T4 templates.

The problem I have is that the Fixup methods are loading hundreds of entities when I assign an associated entity (see line 4 below).

Dim context = New SomeEntities
Dim list = context.Lists.FirstOrDefault(Function(l) l.ListId = 2)
Dim queryDetail = context.CreateObject(Of QueryDetail)()
queryDetail.CriteriaColumnType = context.CriteriaColumnTypes.FirstOrDefault(Function(cct) cct.CriteriaColumnTypeId = 145)

The CriteriaColumnType entity that is being assigned has a collection of QueryDetail objects, and when the assignment is made, the FixUp method on the CriteriaColumnType entity is lazy loading all of the associated QueryDetails.

How can I create the FK association and attach the CriteriaColumnType entity to my QueryDetail entity without loading all of the CriteriaColumnType's QueryDetail records?

A: 

Do you need lazy loading here? You can turn it off:

context.ContextOptions.LazyLoadingEnabled = false
Craig Stuntz
I actually considered using that, but it feels like a hack. Seems hard to believe that the casual Enitity Framework user would really want the associated entitiy's entire collection to be loaded in this case!
Steve Horn
I don't think it's hacky. The context is a unit of work. Not all UOWs need lazy loading. It doesn't have to affect other UOWs, which might need lazy loading.
Craig Stuntz
I agree with Steve. If the only way to avoid this behaior is to turn off the lazy loading, It should be considered as a bug. The only reason for this problem is change tracking (FixUp navigation properties on both sides of association). The code assigns value to navigation property on the one side. It in turn wants to assign the value to navigation collection on the other side but because of accessing the collection it initiates lazy loading.
Ladislav Mrnka
@Ladislav: Actually, I agree that it "feels" like a bug. I didn't mean to imply otherwise. But my general position is that lazy loading is really easy to misuse (as this example demonstrates!), so it should be turned off except when you explicitly need it.
Craig Stuntz
No pun intended, but turning off lazy loading unless required is... lazy. That's a bit backwards. You should only eagerly load the entire object graph is you need the whole object graph.
Andy_Vulhop
Further, if he's complaining about the lazy load happening, there must be a performance hit or something of that nature which would make eager loading equally undesirable.
Andy_Vulhop
@Andy, I'm *not* suggesting eager loading as an alternative. Many times (notably, *this* time) you don't need any loading at all. When you do, projection is often a better choice than eager or lazy loading. In short, it's good to be in full control of what you're doing.
Craig Stuntz