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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

I'd rather not modify my schema just for this.
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.
Oh, I see now. I might do that. Good suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.