简体   繁体   中英

Entity Framework changing values

Ive got a value in a database

public int Rev { get; set; }

and i would like to change it to Rev+1 on each row updates, but since I am new to Entity Framework I have no idea how to program this. Could somebody please help?

You can create a new partial class to override the SaveChanges() method on your EF object. In the SaveChanges() method you can check each entry of YourTableEntity to see if it was modified, and increase the Rev property if it is.

public partial class YourDBNameDBEntities : DbContext
{
    public override int SaveChanges()
    {
        foreach (var entry in this.ChangeTracker.Entries<YourTableEntity>().ToList())
        {
            if (entry.State == System.Data.EntityState.Modified)
            {
                entry.Entity.Rev++;
            }
        }
        return base.SaveChanges();
    }
}

You can create triger, which will increment your field when you update your table.

You can do it by creating a class inherited from a CreateDatabaseIfNotExists or another ones which implemented IDatabaseInitializer and override method Seed.

Here is a short example:

class CdineWithTrigger : CreateDatabaseIfNotExists<RepositoryContext>
{
   protected override void Seed(RepositoryContext context)
   {
      context.Database.ExecuteSqlCommand("YOUR SQL CORE FOR ADDING A TRIGGER");
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM