1

I have an entity class which includes many fields. To make it simple, let's assume the class is defined as following:

public partial class Branches
{

    public int num { get; set; }
    public string name { get; set; }
    public string street { get; set; }
    public string city { get; set; }

In my API class, I want to define a function for updating a record of this type. As creating a function to update each field separately seems like quite an overhead for my application, I decided to define one function that updates all fields. Can I assign the object received by the function directly to the object used for the update as following?

void updateBranch(Branches branch)
{
  using (var dbContext = new entitiesContext())
  {
    var result = dbContext.Branches.SingleOrDefault(b => b.num == branch.num);                                                
    if (result != null)
    {
      **result = branch;**                        
      dbContext.SaveChanges();
    }
  }
}

I'm using Entity Framework version 6.0

Marc Cals
  • 2,963
  • 4
  • 30
  • 48
user648479
  • 15
  • 3
  • "many fields". I'm not sure if you should set the whole entity to `Modified`, see this: http://stackoverflow.com/a/30824229/861716 – Gert Arnold Jun 13 '15 at 22:47

1 Answers1

2

Yes you can use it, with the following code

void updateBranch(Branches branch)
{
    using (var dbContext = new entitiesContext())
    {
        dbContext.Branches.Attach(branch);
        dbContext.Entry(branch).State = EntityState.Modified;              
        dbContext.SaveChanges();
    }
}

When you attach a Entity to DBContext, Entity Framework is aware that this instance exist in database and will perform an update operation.

Marc Cals
  • 2,963
  • 4
  • 30
  • 48