3

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?

Jack
  • 7,433
  • 22
  • 63
  • 107
  • I believe that this: [C# Entity Framework: Can I update a record without querying first?](http://stackoverflow.com/questions/4218566/c-sharp-entity-framework-can-i-update-a-record-without-querying-first) answers your question. – Zbigniew Aug 05 '12 at 08:39

2 Answers2

5

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.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Thank you. Can you also modify the answer for delete? How do I change the above code to delete entity? Can I just do an attach and then remove from DBSet and call SaveChanges? Would that work? – Jack Aug 05 '12 at 10:29
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();
cuongle
  • 74,024
  • 28
  • 151
  • 206