1

I have a table which is a table of pictures and other file types. I want to edit the name field. Normally I would do this:

var file = Db.Files.First(f => f.FileID == id);
file.Name = "NewName";
Db.SaveChanges();

However, in this case this will pull the entire varbinary(max) from the database server for no reason. Is there a way to edit an item without getting the entire EntityObject? Perhaps I can use stub entities or something?

tster
  • 17,883
  • 5
  • 53
  • 72

2 Answers2

3

You can also use this simple trick:

// Define a dummy object
var file = new File { Id = id, Name = "NewName" }; 
// The dummy object attached as Unchanged entity 
context.Files.Attach(file);  
// Get change tracking information about the entity
ObjectStateEntry entry = context.ObjectStateManager.GetObjectStateEntry(file);
// Set Name property to modified
entry.SetModifiedProperty("Name");
// Save changes - only Name property will be modified
context.SaveChanges();

It will save you a query to the database.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
1

You could split the entity into two entities and move the expensive data columns to second entity. Check “Table Splitting”: Mapping multiple entity types to the same table.

amit_g
  • 30,880
  • 8
  • 61
  • 118
  • I'd rather not modify my schema just for this. – tster Mar 23 '11 at 16:55
  • It is not modifying the DB schema. It is the entities that are modified. The underlined table is same. But yes, if you can't or don't want to split the entities also, the only thing I can think of is to use and execute custom SQL that updates only desired column. – amit_g Mar 23 '11 at 18:17
  • Oh, I see now. I might do that. Good suggestion. – tster Mar 23 '11 at 18:19