Search code examples
c#entity-frameworkentity-framework-5ef-database-first

Update an entire record using entity framework


I have a working code here.

using (var db = new MyContextDB())
{
    var result = db.Books.SingleOrDefault(b => b.BookNumber == bookNumber);
    if (result != null)
    {
        result.MyColumnName= "Some new value";
        db.SaveChanges();
    }
}

But I have many properties to change. So I was trying for something like

            result= newResult;
            db.SaveChanges();

But this is not working. Is there any idea to replace a record with a new one?


Solution

  • I think, you can not do this so easily.

    You should create a method in your Book class, where you change all of the properties.

    result.Update(Book newProperties);
    db.SaveChanges();
    

    or

    result.Update(string prop1, int prop2, etc.);
    db.SaveChanges();