问题
I have an employee object say:
public class Employee
{
public int Id {get; set;}
public int Name {get; set;}
public int Address {get; set;}
...other few 10's of properties
}
The question is how do I only update Name? For eg. If I want to update Name I do
Employee e = Db.Employees.Where(e => e.Id == someId).SingleOrDefault();
e.Name = "Jack";
Db.SaveChanges();
As you can see, for updating I have to first get the object and then update and then call SaveChanges(). For a task that can be done in a single query to a database I have to fire of 2 queries: 1) Get the object 2) update the required object and save changes.
For traditional stored procedure approach I would just pass the Id, pass the new Name and write Update statement and I am done. Is Entity Framework really that inefficient or am I missing something?
回答1:
You can update columns selectively:
var employee = new Employee() { Id = someId, Name = "Jack" }
Db.Employees.Attach(employee);
Db.Employees.Entry(employee).Property(e => e.Name).IsModified = true;
Db.SaveChanges();
Note: Only EF 5 with .NET 4.5 supports setting IsModified
back to false
.
回答2:
You should use Attach method
var e = new Employee() { Id = someId, Name = "Jack" }
Db.Employees.Attach(e);
Db.Employees.Entry(e).Property(p => p.Name).IsModified = true
Db.SaveChanges();
来源:https://stackoverflow.com/questions/11814996/updating-record-in-ef-4-1