Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active March 3, 2024 07:35
Show Gist options
  • Save karenpayneoregon/488a26f3084523678463039cf5569717 to your computer and use it in GitHub Desktop.
Save karenpayneoregon/488a26f3084523678463039cf5569717 to your computer and use it in GitHub Desktop.

Used to indicate to EF Core which properties to update.

Example using the following model.

public class Employee
{
	public int Id { get; set; }
	public string Title { get; set; }
	public string FirstName { get; set; }
	public string LastName { get; set; }
	public DateTime? BirthDate { get; set; }
}

We only want to update first and last name. Here a valid Employee is passed in

public (bool, Exception exception) UpdateFirstNameAndLastName(Employees employees)
{
	try
	{
		_context.Employees.Attach(employees);
		UpdateSpecificField(employees, x => x.FirstName, x => x.LastName);
		var affected = _context.SaveChanges();
		return (affected == 1, null)!;
	}
	catch (Exception localException)
	{
		return (false, localException);
	}
}
public void UpdateSpecificField(Employees entity, params Expression<Func<Employees, object>>[] updatedProperties)
{
foreach (var property in updatedProperties)
{
_context.Entry(entity).Property(property).IsModified = true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment