Hello,
I've read the following in the documentation:
Option 2 is more efficient in that it just starts an update, without first reading the data from the database. The following code performs the same update as the previous example code illustrating option 1. Even though the PK field is changed, it is not updated, because it is not previously fetched from the database.
C#VB.NET
// [C#]
CustomerEntity customer = new CustomerEntity();
customer.CustomerID="CHOPS";
customer.IsNew=false;
customer.Phone = "(605)555-4321";
customer.Save();
We have to set the primary key field, so the Update method will only update a single entity, the "CHOPS" entity. Next, we have to mark the new, empty entity object as not being new, so Save() will call the Update method, instead of the Insert method. This is done by setting the flag IsNew to false. Next is the altering of a field, in this case "Phone", and the call of Save(). This will not load the entity back in memory, but because Save() is called, it will be marked out of sync, and the next time you'll access a property of this entity's object, it will be refetched from the persistent storage. Doing updates this way can be very efficient and you can use very complex update constructs when you apply an Expression to the field(s) to update. See for more information about Expression objects for fields Field expressions and aggregates.
Now I try this code for myself:
public void UpdateLocation(int locationId, string name, string reception, string email)
{
//Make a new instance of LocationEntity. Since IsNew is false and the primary key (LocationId) is set an update query will be executed.
LocationEntity locationEntity = new LocationEntity()
{
IsNew = false,
LocationId = locationId,
Name = name,
Reception = reception,
Email = email
};
//Update the row into sql server.
locationEntity.Save();
}
I did this before if the GUID was a primary key, but now I use an int with identity seed and I get the following exception:
The field 'LocationId' is read-only and can't be changed
What am I doing wrong?