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

1

1 Answer 1

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.

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

3 Comments

This causes an error saying that the lambda expression is not a delegate type.
sorry, still not working :( I see the original record without the modifications
Try now! without modified EF thought that nothing was changed in the object!

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.