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 som开发者_开发百科ething?
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.
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.
精彩评论