How to Update Only One Field Using Entity Framework

How to update only one field using Entity Framework?

Ladislav's answer updated to use DbContext (introduced in EF 4.1):

public void ChangePassword(int userId, string password)
{
var user = new User() { Id = userId, Password = password };
using (var db = new MyEfContextName())
{
db.Users.Attach(user);
db.Entry(user).Property(x => x.Password).IsModified = true;
db.SaveChanges();
}
}

How to only update specific fields in Entity Framework (Core)

You have to update entity returned by the EF.

string apiResponse = await response.Content.ReadAsStringAsync();

var data = JsonConvert.DeserializeObject<List<Customers>>(apiResponse);

foreach (Customers customer in data)
{
var current = db.Customers.Find(customer.BranchId);
if (current != null)
{
db.Entry(current).CurrentValues.SetValues(customer);
}
else
{
db.Customers.Add(customer);
}

db.SaveChanges();
}

Update specific fields in Entity Framework

You can Attach the entity to avoid loading it from DB (save performance) and update only the fields you want.

This also avoids the problem of your code when you load an instance from the DB (Result) and track another instance with the same Id (vR) resulting in an exception.

// POST: VRs/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(VR vR)
{
if (ModelState.IsValid)
{
//Attach the instance so that we don't need to load it from the DB
_context.MyVR.Attach(vR);

vR.ModifiedBy = User.Identity.Name;
vR.Modified = DateTime.Now;

//Specify the fields that should be updated.
_context.Entry(vR).Property(x => x.ModifiedBy).IsModified = true;
_context.Entry(vR).Property(x => x.Modified).IsModified = true;

_context.SaveChanges();
return RedirectToAction("Index");
}
return View(vR);
}

The other way to specify fields that should not be updated.

// POST: VRs/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(VR vR)
{
if (ModelState.IsValid)
{
//Attach the instance so that we don't need to load it from the DB
_context.Entry(vR).State = EntityState.Modified;

vR.ModifiedBy = User.Identity.Name;
vR.Modified = DateTime.Now;

//Specify the fields that should not be updated.
_context.Entry(vR).Property(x => x.Created).IsModified = false;
_context.Entry(vR).Property(x => x.CreatedBy).IsModified = false;

_context.SaveChanges();
return RedirectToAction("Index");
}
return View(vR);
}

In case you use a view model, you can use new operator to create your data model and copy the fields you want to update:

// POST: VRs/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit(VRViewModel vRVM)
{
if (ModelState.IsValid)
{
VR vR = new VR();
//Attach the instance so that we don't need to load it from the DB
_context.MyVR.Attach(vR);

//Set the Id for your model.
vR.Id = vRVM.Id;
//Let's say you also want to update this field from the VM
vR.FullName = vRVM.FullName;

vR.ModifiedBy = User.Identity.Name;
vR.Modified = DateTime.Now;

//Specify the fields that should be updated.
_context.Entry(vR).Property(x => x.ModifiedBy).IsModified = true;
_context.Entry(vR).Property(x => x.Modified).IsModified = true;
_context.Entry(vR).Property(x => x.FullName).IsModified = true;

_context.SaveChanges();
return RedirectToAction("Index");
}
//create your new view model and return it. For demonstration purpose, I return the same view model, in your real code, you can adjust it.
return View(vRVM);
}

Update only one field in EF Core

I update it by below code

 public async Task updateUserInfo(string token,long  userId)
{
User user = _userRepository.GetDbContext().Set<User>().Find(userId);

user.token= token;

_userRepository.GetDbContext().Set<User>().Attach(user);

_userRepository.GetDbContext().Entry(user).Property(x => x.token).IsModified =true;
await _userRepository.GetDbContext().SaveChangesAsync();
}

How to update one field of specific records using Entity Framework?

You are missing an Id field when creating an instance of Person object. Because of this Entity Framework is not able to find an existing Person.

Your code should look like this:

public static void Update(int id, string name, string family)
{
var _person = new Person() { Id = id , FirstName = name, LastName = family };

using (var newContext = new MyDbContext())
{
newContext.Persons.Attach(_person);
newContext.Entry(_person).Property(X => X.LastName).IsModified = true;
newContext.SaveChanges();
}

Update one column and set all values to 1 using Entity Framework

You need to load the existing records, modify them and then save the changes, e.g.

var notYetDoneCustomers = await context.Customers.Where(c => c.DoneFlag == 0).ToListAsync();

foreach(var cust in notYetDoneCustomers) {
cust.DoneFlag = 1;
}

await context.SaveChangesAsync();

Only update specific column using Z.EntityFramework.Plus' SingleUpdate method

You can achieve it by using the Where and UpdateFromQuery:

await db.Features.Where(x => x.ID == featureInfo.ID).UpdateFromQuery(x => new Feature()
{
Unit = unit
});

For multiple IDs, if the unit is a constant:

await db.Features.Where(x => ids.Contains(x.ID)).UpdateFromQuery(x => new Feature()
{
Unit = unit
});

If you have thousand/million IDs, is also possible to use the WhereBulkContains method (this one is not free):

await db.Features.WhereBulkContains(ids).UpdateFromQuery(x => new Feature()
{
Unit = unit
});

EDIT: Answer Comment

Is there any documentation for the SingleUpdateAsync method I was using

There is no documentation. It works exactly like BulkUpdate but allows you to pass a single entity instead of a list (this is the only difference).



Related Topics



Leave a reply



Submit