tster
tster

Reputation: 18237

Modify field with Entity Framework without EntityObject

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?

Upvotes: 1

Views: 419

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

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.

Upvotes: 3

amit_g
amit_g

Reputation: 31250

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.

Upvotes: 1

Related Questions