Search code examples
c#.netentity-frameworklinq-to-entitiesgarbage-collection

How to update an existing object's properties using LINQ to Entities?


LINQ to Entities allows this:

context.User.Select(u => new Person
{
    Name = u.Name,
    Parent = u.Parent.Name
});

I need only two properties of a big User table and I get them using the Select method to create a Person object so I can do some processing with it. The thing is that I do this a lot (like twice a second) and it hurts the GC.

So I decided to pool the Person objects but I have no idea how to update an existing object using LINQ to Entities. I can get it as an anonymous method like above and then assign its properties to the depooled object I guess, then I can return the depooled instance, this would at least make the anonymous instance go away in a lower generation of GC but...

I'd really prefer something like this:

context.User.Select(u => People.Take(u.Name, u.Parent.Name))

Which throws a NotSupportedException.

  • Can I use Entity Framework to update the values of an existing object?
  • If so, how?
  • If not, what alternatives do I have?

Solution

  • Can I use Entity Framework to update the values of an existing object?

    No - the Select method is used for projection not updating - what your doing is the correct approach. Alternatively you may find it more efficient to change your Person class to a struct as it consumes less memory.

    I think you need to elaborate a little more on "It hurts the GC".

    Update

    It appears Linq to Entities does not support projecting onto struct's (seems like a limitation to me) - best possible approach then would be to just project onto an anonymous type & then you can map your results onto your Person class using your pooling mechanism e.g.

    var users = (from u in context.User
                select new {
                    Name = u.Name,
                    Parent = u.Parent.Name
                }).ToList().Select(u => People.Take(u.Name, u.Parent));