Several methods of EF CORE update

1. Query before modifying

The entity is obtained by context, so the context immediately begins to trace it. When you change the tracking entity's property value, the context changes the entity's EntityState to Modified, and ChangeTracker records the old and new property values. When SaveChanges is called, the database generates and executes an UPDATE statement. If it is found that the Modified value is the same as the original value, State is unchanged

  var user = testDbContext.User.Include(a => a.Orders).First(a => a.UserId == 1);
            user.FirstName = "zhang";
            EntityState ss = testDbContext.Entry(user).State;//unchanged
            testDbContext.SaveChanges();
            user.FirstName = "zhang1";
            EntityState ss1 = testDbContext.Entry(user).State;//modifed
            testDbContext.SaveChanges();
var author = context.Authors.First(a => a.AuthorId == 1);
author.FirstName = "Bill";
context.SaveChanges();
exec sp_executesql N'SET NOCOUNT ON;
UPDATE [Authors] SET [FirstName] = @p0
WHERE [AuthorId] = @p1;
SELECT @@ROWCOUNT;
',N'@p1 int,@p0 nvarchar(4000)',@p1=1,@p0=N'Bill'

2. Set the state of EntityState

   public void updateEntityState()
        {
            User u = new User();
            u.FirstName = "zhang";
            u.UserId = 1;
            testDbContext.Entry(u).State = EntityState.Modified;
            testDbContext.SaveChanges();

        }
 UPDATE[User] SET[DefaultCurrencyCode] = @p0, [FirstName] = @p1, [LastName] = @p2, [SecurityLevel] = @p3
            WHERE[UserId] = @p4;
            SELECT @@ROWCOUNT;

Although two properties are defined and modified in the code, this method still sets the undefined property value to null.

3. Call the Update () method of EF CORE

public void update()
        {
            User u = new User();
            u.DefaultCurrencyCode = "USD";
            u.FirstName = "zhang";
            u.LastName = "feng";
            u.SecurityLevel = 1;
            u.UserId = 1;
            testDbContext.Update(u);
                EntityState ss = testDbContext.Entry(u).State;
            testDbContext.SaveChanges();

        }
           UPDATE[User] SET[DefaultCurrencyCode] = @p0, [FirstName] = @p1, [LastName] = @p2, [SecurityLevel] = @p3
 WHERE[UserId] = @p4;
SELECT @@ROWCOUNT;

 

The difference between this method and explicitly setting the State property is that the context will start tracking any related entities with a Modified State, generating an UPDATE statement for each entity. If the relation table has no key value assigned and the relation entity class is not empty, it will be marked as "added" and an INSERT statement will be generated. In this way, the undefined property value will also be set to null (will generate SQL to update all properties)

4.Attach

When you use the Attach method on an entity, its state is set to Unchanged, which causes no database commands to be generated at all. All other associated entity classes that have key values defined will also be set to Unchanged. If the relationship entity class does not have a key value assigned, and the relationship entity class is not empty, it is marked "added". You can trace any attribute in any entity class and set state to modified

 public void updateAttach()
        {
            User u = new User();
            u.FirstName = "zhang";
            u.UserId = 2;
            testDbContext.Attach(u);
            testDbContext.Entry(u).State = EntityState.Modified;
            testDbContext.SaveChanges();

        }
UPDATE[User] SET[FirstName] = @p0
 WHERE[UserId] = @p1;
SELECT @@ROWCOUNT;

5.TrackGraph

The TrackGraph API provides access to individual entities of an object and enables you to execute custom code individually for each entity. This is useful when dealing with complex objects that are composed of various related entities in different states.

 public void updateTrack()
        {
            var u = new User
            {
                UserId = 1,
                FirstName = "William",
                LastName = "Shakespeare"
            };
            u.Orders = new List<Order>();
            u.Orders.Add(new Order { Address = "test1",OrderId=1002 });



            testDbContext.ChangeTracker.TrackGraph(u, e => {
                if ((e.Entry.Entity as User) != null)
                {
                    e.Entry.State = EntityState.Unchanged;
                }
                else
                {
                    e.Entry.State = EntityState.Modified;
                }
            });
            testDbContext.SaveChanges();
        }

Here, testDbContext.ChangeTracker.TrackGraph will loop all entity classes under user including itself, so if ((e.entry. Entity as user)! = null) if we don't need update user.
                {
                    e.Entry.State = EntityState.Unchanged;
                }

In this way, all the properties of entity classes will be updated. The Timestamp field cannot exist in the database table. Otherwise, you may need to make some other settings, or the update will not succeed.

Keywords: Database P4 SQL Attribute

Added by tekkenlord on Sun, 27 Oct 2019 09:09:51 +0200