Entity Framework Core updating unchanged fields - entity-framework-core

I'm not sure if this is a question about Entity Framework, or how the audit.net library works, but I was guessing it was with how I was performing updates with EF. My goal is to capture only actual changes to the record, but it's capturing everything as change, even if the old and new values are identical.
Basically to simplify it as much as possible, if I do
var existing = context.Appl.FirstOrDefault(a => a.Id == id);
context.Appl.Update(existing);
context.SaveChanges();
(Changing nothing)
The Audit.Net change log says every single field was changed, and looks like
"Changes": [
{
"ColumnName": "FOO",
"OriginalValue": "",
"NewValue": ""
},
..... many more

My goal is to capture only actual changes to the record
Then you should not use the Update method.
According to the Update method documentation:
Begins tracking the given entity in the Modified state such that it will be updated in the database when SaveChanges() is called.
All properties of the entity will be marked as modified. To mark only some properties as modified, use Attach(Object) to begin tracking the entity in the Unchanged state and then use the returned EntityEntry to mark the desired properties as modified.
The main usage case for Update method is to perform a so called forced update when working with Disconnected Entities. Since your existing entity is retrieved from the context (or in other words, is tracked by the context), hence all you need is to set the new values. Change tracker will detect if there are actual property changes and will issue UPDATE command with only modified values (or no UPDATE command at all if all current values are equal to the original values).

Related

"Cannot insert explicit value for identity column in table 'x' when IDENTITY_INSERT is set to OFF" - inserting record with nested custom object

I get the error "Cannot insert explicit value for identity column in table 'UserPermission' when IDENTITY_INSERT is set to OFF" trying to insert a record as follows:
dbContext.User.Add(someUser);
dbContext.SaveChanges();
That being said, the User file has the custom class UserPermission as one of its parameters, and someUser's UserPermission is not null and has a set ID parameter. Why does this happen and is it possible to avoid getting this error without having to explicitly add a UserPermissionID foreign key parameter in my User model and setting the UserPermission parameter to null?
Thanks in advance.
This issue typically happens when deserializing entities that have related entities in the object graph then attempting to add them. UserPermission is likely an existing record that in the DB is set up with an identity PK, but EF doesn't appear to recognize that in the entity definition. (I.e. set to DatabaseGenerated(DatabaseGeneratedOption.Identity). If it had been you would most likely be seeing a different problem where a completely new duplicate UserPermission was being created.
If someUser, and it's associated someUser.UserPermission are deserialized entities then you need to do a bit of work to ensure EF is aware that UserPermission is an existing row:
void AddUser(User someUser)
{
var existingPermission = _context.UserPermissions.Local
.SingleOrDefault(x => x.UserPermissionId == someUser.UserPermission.UserPermissionId);
if (existingPermission != null)
someUser.UserPermission = existingPermission;
else
_context.Attach(someUser.UserPermission);
_context.Users.Add(someUser);
_context.SaveChanges();
}
In a nutshell, when working with detached entities that a DbContext may not be tracking, we need to check the Local state for any existing tracked instance for that ID. If we find one, we substitute the detached reference for the tracked one. If we don't find one, we attach the detached one before Adding our user.
This still isn't entirely safe because it assumes that the referenced UserPermission will exist in the database. If for any reason a non-existent UserPermission is sent in (row deleted, or fake data) you will get an exception on Save.
Passing detached entity references around can seem like a simple option at first, but you need to do this for every reference within a detached entity. If you simply call Attach without first checking, it will likely work until you come across a scenario where at runtime it doesn't work because the context happens to already be tracking an instance.

EF Core: updating an entity without querying it first

I'm looking for a way to update a property of an entity by knowing its primary key, without first querying it.
The solution I've come up with is this one:
var order = new OrderEntity()
{
Id = 5
};
db.Orders.Attach(order).State = EntityState.Unchanged;
order.Name = "smth";
db.SaveChanges();
Which seems to work fine, as the generated SQL is exactly what I expect:
UPDATE "Orders" SET "Name" = #p0
WHERE "Id" = #p1;
Question: is this the correct way of doing it?
I can't find any confirmation about this in the official documentation, or anywhere else on the web actually. Similar questions are about Entity Framework (non-Core) and they seem to use different strategies, like setting EntityState.Modified instead of Unchanged. I tried that as well but it has the effect of updating all the properties, which is not what I want to achieve. So I'm wondering if there's something I'm missing about the solution above.
Thanks.
The documentation for DbContext.Attach Method says:
Begins tracking the given entity and entries reachable from the given entity using the Unchanged state by default, but see below for cases when a different state will be used.
[...]
For entity types with generated keys if an entity has its primary key value set then it will be tracked in the Unchanged state. If the primary key value is not set then it will be tracked in the Added state.
[...]
For entity types without generated keys, the state set is always Unchanged.
[...]
So setting the state to Unchanged is not even necessary.
But be careful. If you set e.g. order.Amount = 0m; to clear the amount, this will not work, as no change will be detected. Write
var order = new OrderEntity()
{
Id = 5,
Amount = 1.00m; // Dummy value unequal 0.00m
};
db.Orders.Attach(order);
// Make the change
order.Amount = 0.00m; // Now, this change will be detected.
db.SaveChanges();

Entity Framework Update Fails for Entity With ID of 0

Using Entity Framework Core 3.0 and facing an odd issue where EF will throw an exception if I try to update an entity with ID=0, it thinks that ID=0 is a temporary value. Same code updates entity with ID=1 or higher without any problems.
Exception:
InvalidOperationException: The property 'Id' on entity type 'MyType' has a temporary value
while attempting to change the entity's state to 'Modified'. Either
set a permanent value explicitly or ensure that the database is
configured to generate values for this property.
Exception is triggered on the following statement:
_context.Attach(MyType).State = EntityState.Modified;
I don't want to reseed all my tables to start with 1.
Is this expected behavior with EF? It should be possible to save entities with ID=0.
Any advice on how to resolve this?
Thanks.
You have to do something about this zero ID value. It's a ticking time bomb.
You'll always have to be on your guard because it definitely is expected behaviour. EF has inner logic depending on key default values. In EF6 you could do this because it was less refined. (In this area that is).
Let me show you how leaving this ID value can backfire on you in the future.
You have this MyType object. Let's call it entity to follow some naming conventions/habits. Its ID value is 0 and it's not attached to the context.
Now suppose you don't use this rather redundant way to attach it as modified but the new EF-core way:
context.Update(entity);
Now you won't see any exception, but no, the issue isn't fixed. It's gotten worse. The entity object's state is Added now and you're going to add a new record to your table. That might even go unnoticed for a while, adding to the pile of mess you have to clean up later.
Had its ID value been > 0, EF's Update method would have concluded it's an existing entity and its state should be Modified.
You can set entity's state to Modified if (1) it's not attached and (2) you use...
context.Entry(entity).State = EntityState.Modified;
And that's another time bomb. Later code changes remove the first condition (it's not attached) and boom.

Entity Framework 6 - Always update properties that were manually setted by code - Change behavior of change tracker in proxy classes

This is Entity Framework 6.1.3 with .NET v4.0 and SQL Server 2008 R2.
In my, DB I have hundreds of tables with column LastChangedByUser in which I store the login of the user who last updated the row.
Unfortually, I have legacy triggers FOR UPDATE on almost all tables, and they all verify IF UPDATE(LastChangedByUser) and raise an error if this column is not included in the SET clause of the updated. I suppose the original developers did this to make sure the developers included every required column in their manually-written update queries.
By default EF only includes the properties that had their values changed when generating the SET clause of an UPDATE query. And this is causing problems in the following scenario: If previously some row was last changed by "user1", and the same "user1" tries to updates this row again later, EF is not including the LastChangedByUser column in it's generated SET clause, since it was set to the same value that it previously had. And the trigger is raising the error.
My legacy system (pre-EF) includes the LastChangedByUser in the SET clause in manually-written queries, regardless of the value being unaltered, so the trigger validations do OK for those old queries.
So I need to "mimic" this behavior in Entity Framework: if the code explicitly set a property value of a bound Entity proxy, I need its corresponding DbPropertyEntry to have the IsModified set to true regardless of the value being the same as the previous value.
I don't want to include all the columns in the SET cause (I tried this and had other trigger problems). I just want to include the columns that were set explicitly, like:
//this should make the property IsModified become true
//even if it was already "user1" when the entity loaded
myEntity.LastChangedByUser = "user1";
If the code simply dos not change the property (the setter is never called), then the property should remain with IsModified == false.
Is it possible to solve this? Maybe this default behaviour is too intrinsic and can't be changed...
Unfortunately I cannot just disable/drop the triggers, since they do tons of business rules on which the legacy system is dependent. And they are hundreds, so editing each one of them will be really tough...
Thank you!

Store update insert or delete statement affected an unexpected number of rows (0)

I'm using the code show below to update an entity model. But I get this error:
Store update, insert, or delete statement affected an unexpected number of rows (0)
And reason of this error is also known, it's because the property does not exist in the database. For that I found have only one option: first check that the entity exists, then update it.
But, as I'm updating 10,000+ rows at a time, it will be time consuming to check each time in database if this property exist or not.
Is there any another way to solve this ?
Thank you.
foreach (Property item in listProperties)
{
db.Properties.Attach(item);
db.Entry(item).Property(x => x.pState).IsModified = true;
}
db.SaveChanges();
You use it the wrong way. If you want to update without retrieving the entity, just change the state of the updated entity with providing the id.
foreach (Property item in listProperties)
{
db.Entry(item).State = EntityState.Modified;
}
db.SaveChanges();
Attaching an existing but modified entity to the context
If you have an entity that you know already exists in the database but
to which changes may have been made then you can tell the context to
attach the entity and set its state to Modified.
When you change the state to Modified all the properties of the entity
will be marked as modified and all the property values will be sent to
the database when SaveChanges is called.
Source
I got this error Just by updating EF version from 5 to 6 solved the issue.