Repository navigation
How To Update
This guide shows how you can update existing rows in a database from instances of entities. It assumes you have followed one of the Getting Started guides Getting Started (IoC) or Getting Started (Static) and have created a repository.
We recommend you use this explicit update method as it gives you more control of the SQL generated and what values actually get updated. We provide an alternative implicit update method, which is detailed below but as you will see it has potential issues. With the explicit method you have full control of which columns are given values allowing things like default constraints to be applied.
var result = repository.Update()
.Set(e => e.IsCompleted, true)
.Where(e => e.Id == myEntity.Id)
.Go();Here we have updated the only value we want to change all other columns in the table will remain unchanged.
The Set() method takes an expression for the member to be set and a value, it can be called for each member that should have a value set.
As with any SQL UPDATE it is important to set a WHERE clause to ensure only the appropriate rows are changed. The Where() method accepts a boolean expression that will be translated into an equivalent WHERE clause in the generated SQL.
The simplest way to update a database row for an entity instance is to pass the instance to the repository Update method. However SqlRepo has no knowledge or how the entity maps to the relevant table so it will generate a statement that sets a value for every writable property of the entity, even if that property value is null. This could cause unexpected results overwriting values that were not intended.
repository.Update(myEntity);Note you don't have to call Go() in this case the statement is generated and executed immediately. This is shorthand for the following, which is what is actually executed.
repository.Update().For(myEntity).Go();