Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic CreatedAt and UpdatedAt fields OnModelCreating() in ef6

I have CreatedAt and UpdatedAt columns in my User model.

User.cs

public string Name { get; set; }
public DateTime? CreatedAt { get; set; }
public DateTime? UpdatedAt { get; set; }

Requirement

  • When we SaveChanges() user records, CreatedAt and UpdatedAt should automatically saved e.g: DateTime.UtcNow
  • When I update User record, only UpdatedAt column should get updated to current date time.
  • And this should happen automatically for all other models, may be some configuration in OnModelCreating().
  • I want this behavior to find latest records from the database, and other places too.
  • I am using code first migration approach
  • I am using MySQL server, MySql.Data, MySql.Data.Entity.EF6.

UPDATE

I added BaseEntity.cs model

public abstract class BaseEntity
    {
        public DateTime CreatedAt { get; set; }
        public DateTime UpdatedAt { get; set; }
    }

Inheriting User from BaseEntity

public class User : BaseEntity
{
  public int Id { get; set; }
  public int FullName { get; set; }
}

and updated migrations to include defaultValueSql()

AddColumn("dbo.Users", "CreatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "NOW()"));
AddColumn("dbo.Users", "UpdatedAt", c => c.DateTime(nullable: false, precision: 0, defaultValueSql: "NOW()"));"

Now, need a way to fix UpdatedAt column in each update.

like image 708
przbadu Avatar asked Aug 01 '17 05:08

przbadu


People also ask

How do I create an EF model?

There are two main ways to create an EF model: 1 Using Code First: The developer writes code to specify the model. EF generates the models and mappings at runtime based... 2 Using the EF Designer: The developer draws boxes and lines to specify the model using the EF Designer. The resulting... More ...

Is it possible to automatically update the modified date in EF?

EF Core 2.0 includes a feature of generating a date in the database whenever a new record is added using data annotation attribute DatabaseGenerated. However, as of now, EF Core 2.0 does not include a feature to automatically update the modified date. Consider the following entity with CreatedDate and UpdatedDate properties.

Is it possible to add a created Date column automatically with EF6?

Contact CV Andy Mehalick Software Engineer, Founder, CTO EF6: Adding a Created Date/Time Column Automatically with Code First Migrations 6 February 2014 Here’s a quick one, I’m using EF6 code first migrations and I want to add a created date/time column to every table in the database.

What is an Entity Framework (EF) model?

An EF model stores the details about how application classes and properties map to database tables and columns. There are two main ways to create an EF model: Using Code First: The developer writes code to specify the model.


1 Answers

Finally, Found solution for my problem. Because we can change our database from MySql to postgresql or Ms Sql server, so adding default value using sql query doesn't seems like correct solution.

Here is how I have solved it.

Add Base model

 public abstract class BaseEntity
 {
    public DateTime? CreatedAt { get; set; }
    public DateTime? UpdatedAt { get; set; }
 }

Inherit all your models from this base model, In my case it is User

public class User : BaseEntity
{
  public int Id { get; set; }
  public int FullName { get; set; }
}

don't forget to generate migrations if you are using code first approach. Migration should be simple enough:

Example:

AddColumn("dbo.Users", "CreatedAt", c => c.DateTime(precision: 0));
AddColumn("dbo.Users", "UpdatedAt", c => c.DateTime(precision: 0));

And Final step is to override SaveChanges() and SaveChangesAsync() in your context:

public class MyDbContext : DbContext
{
    public DbSet<User> Users { get; set; }

    public override int SaveChanges()
    {
        AddTimestamps();
        return base.SaveChanges();
    }

    public override async Task<int> SaveChangesAsync()
    {
        AddTimestamps();
        return await base.SaveChangesAsync();
    }

    private void AddTimestamps()
    {
        var entities = ChangeTracker.Entries()
            .Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));

        foreach (var entity in entities)
        {
            var now = DateTime.UtcNow; // current datetime

            if (entity.State == EntityState.Added)
            {
                ((BaseEntity)entity.Entity).CreatedAt = now;
            }
            ((BaseEntity)entity.Entity).UpdatedAt = now;
        }
    }
}
like image 105
przbadu Avatar answered Nov 14 '22 21:11

przbadu