Friday, February 11, 2011

Why cant I use lambda when serializing DataContract?

Made som mock code below to illustrate my example. The problem is the lambda expression. If I leave it as in the code example it will not serialize when I try to call the service. However if I type .ToList() after the lambda it serializes as it should.

Why is that? I can't see why the code below should not work... Anyone care to enlighten me? :)

var list = new EntityPerson
               {
                   Names = modelPerson.Names.Select(
                                     n => new EntityName
                                              {
                                                   Text = n.Text
                                              })
                }
  • That's because of the deferred execution. You're not storing the result of the lambda execution, but rather the expression tree or lambda itself, which would need to serialize a reference (!) to the modelPerson.

    http://blogs.msdn.com/b/charlie/archive/2007/12/09/deferred-execution.aspx and many more show the "problems" associated with this. (Google for "deferred execution .net" for more.)

    debe : Yeah i knew about that but still thought that it would run the query before serializing... Thanks for the quick response
    From Lucero

0 comments:

Post a Comment