Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework partial load

I have the following columns in my table

  • Id (int)
  • Name (nvarchar) usually < 100 characters
  • Data (nvarchar) average 1MB

I'm writing a program that will go through each row and perform some operations to the Name field. Since I'm only using the Name field and the Data field is very large, is it possible to direct EF to only load the Id and Name field?

like image 646
James Avatar asked Oct 01 '12 06:10

James


People also ask

How lazy loading works in Entity Framework?

Lazy loading is the process whereby an entity or collection of entities is automatically loaded from the database the first time that a property referring to the entity/entities is accessed. Lazy loading means delaying the loading of related data, until you specifically request for it.

Does Entity Framework support lazy loading?

Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

How do I turn off lazy loading in Entity Framework?

We can disable lazy loading for a particular entity or a context. To turn off lazy loading for a particular property, do not make it virtual. To turn off lazy loading for all entities in the context, set its configuration property to false.

What is the difference between eager and lazy loading in Entity Framework?

While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.


1 Answers

Sure is

ctx.YourDbSet.Select(p=> new { Id = p.Id, Name = p.Name});

this method is selecting into an anonymous class.

if you want to save this back again you can do this with something which I call a dummy entity:

foreach(var thing in ctx.YourDbSet.Select(p=> new { Id = p.Id, Name = p.Name}))
{
    var dummy = new YourEntity{Id = thing.Id};
    ctx.YourDbSet.Attach(dummy);
    dummy.Name = thing.Name + "_";
}
ctx.SaveChanges();

This method works with snapshot tracking as EF only tracks changes made after the attach call to send back in the update statement. This means your query will only contain an update for the name property on that entity (ie it wont touch data)

NOTE: you want to make sure you do this on a context you tightly control as you cant attach an object which is already attached to the EF tracking graph. In the above case the select will not attach entities to the graph as its anonymous (so you are safe using the same context)

like image 100
Not loved Avatar answered Oct 19 '22 23:10

Not loved