Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 471
Şafak Gür Avatar asked Dec 05 '25 12:12

Şafak Gür


2 Answers

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));
like image 76
James Avatar answered Dec 08 '25 02:12

James


You can not pull only few properties of object from DB. If you want to update it, you have to get complete object, update it and then save changes.

But if you really need to update few fields and don't want to move full object, you can use ExecuteStoredCommand method of context object(MySQL example):

    context.ExecuteStoredCommand("UPDATE table1 SET field1 = @value1 WHERE field2 = @value2", new MySqlParameter("@value1", 1), new MySqlParameter("@value2", 2))

It requires you to write some SQL code, but saves your time, because you don't need to worry about opening connection, creating command and other things, required to user regular connector

like image 26
Uriil Avatar answered Dec 08 '25 01:12

Uriil