views:

116

answers:

2

Ex 1:

"autor.ComentariosWorkItens.Add(comentarioWorkItem);"

autor.ComentariosWorkItens makes EF4 load all ComentariosWorkItens.

Ex 2:

comentarioWorkItem.Usuario = autor;

Fixup make EF load all ComentariosWorkItens too:

    private void FixupUsuario(Usuario previousValue)
    {
        if (previousValue != null && previousValue.ComentariosWorkItens.Contains(this))
        {
            previousValue.ComentariosWorkItens.Remove(this);
        }

        if (Usuario != null)
        {
            if (!Usuario.ComentariosWorkItens.Contains(this))
            {
                Usuario.ComentariosWorkItens.Add(this);
            }
        }
    }

How can I prevent this?

A: 

1: Turn it around:

comentarioWorkItem.Usario = autor;

2: How is the EF supposed to answer this:

previousValue.ComentariosWorkItens.Contains(this)

... without looking into ComentariosWorkItens?

Craig Stuntz
With a Select Exists.Another example: autor.ComentariosWorkItens.Count. EF4 select full table too, but just need a Select count.I think NHibernate call this "Extra Lazy"
Fujiy
Don't confuse `ObjectQuery` and `EntityCollection`. `MyObjectContext.Usarios.Where(u => u.Id == id).Firsd().ComentariosWorkItems.Count()` will *not* select all rows for the user. Doing the same on an instance will. Learn the difference between LINQ to Objects and LINQ to Entities.
Craig Stuntz
But will select all ComentariosWorkItems table
Fujiy
No, that is not right. `from u in MyObjectContext.Usarios where u.Id == id select u.ComentariosWorkItems.Count()` does a `SELECT COUNT ... WHERE`, not the whole table. Profile the SQL and see for yourself. (Fixed syntax error in first ex.)
Craig Stuntz
I dont tested this way. But if I first select user, and them user.ComanteariosWorkItems.Count(). EF4 select all ComanteariosWorkItems for that user. Ayende confirm this at my comment at: http://ayende.com/blog/archive/2010/01/05/nhibernate-vs.-entity-framework-4.0.aspx
Fujiy
I know that you're not doing it the way that I suggest and that if you do it the wrong way then you will get the wrong results. That is why I showed you the correct way to do it without selecting all records. You can either do it the way I suggest and have the SELECT COUNT or you can continue to do it your way and get poor performance.
Craig Stuntz
A: 

I sent a email to Julie Lerman. Here her answer:

"I think this is known (and AWFUL) behavior on EF’s part. I’m not sure what to tell you. You might want to take a look in the MSDN forums to see if anyone from the team has anything to say about it. And, since I’m in the middle of reviewing my book before it goes to print, I will check to be sure I have a warning about this in there somewhere!"

Fujiy