entity framework update record code example
Example 1: entity framework update child records
public void Update(UpdateParentModel model)
{
var existingParent = _dbContext.Parents
.Where(p => p.Id == model.Id)
.Include(p => p.Children)
.SingleOrDefault();
if (existingParent != null)
{
_dbContext.Entry(existingParent).CurrentValues.SetValues(model);
foreach (var existingChild in existingParent.Children.ToList())
{
if (!model.Children.Any(c => c.Id == existingChild.Id))
_dbContext.Children.Remove(existingChild);
}
foreach (var childModel in model.Children)
{
var existingChild = existingParent.Children
.Where(c => c.Id == childModel.Id)
.SingleOrDefault();
if (existingChild != null)
_dbContext.Entry(existingChild).CurrentValues.SetValues(childModel);
else
{
var newChild = new Child
{
Data = childModel.Data,
};
existingParent.Children.Add(newChild);
}
}
_dbContext.SaveChanges();
}
}
Example 2: how to update record using entity framework 5
BY LOVE SINGH.
employeeDBEntities.tblEmployee.Attach(objTblEmployee);
employeeDBEntities.Entry(objTblEmployee).State = EntityState.Modified;
employeeDBEntities.SaveChanges();
Example 3: how to update record using entity framework in c#
public void UpdateCustomer(Customer custDTO)
{
CustomerEntities ce = new CustomerEntities();
Customer cust = ce.Customers.Find(custDTO.Id);
if (cust != null)
{
DbEntityEntry<Customer> ee = ctx.Entry(cust);