7

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?

James
  • 2,811
  • 3
  • 25
  • 29

1 Answers1

10

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)

undefined
  • 33,537
  • 22
  • 129
  • 198
  • the only problem is that I need to save the changes to p.Name – James Oct 01 '12 at 06:45
  • @NotLoved Can you please give an example on the 'NOTE:' part of your answer? So if you had done for eg: `var myEntity = ctx.YourDbSet.First()`, that means `myEntity` is already attached to the graph and I won't be able to make any updates to that entity? Also can you please elaborate on 'so you are safe using the same context' part with an example? Thank you! – Ash K Nov 22 '21 at 20:14