none
Auto Generated Created Updated DateTime on EntityFramework 6 RRS feed

  • Question

  • Hello,

    I want to have CreatedDate / UpdatedDate autoGenerated on Entity Framework 6.

    As its easy to do on EF 7 (EF core) using OnModelBuilder, i didnt find any relevant articles helping me to achieve the same goal on EF 6.

    My configuration is automated migration in code first. I dont have any models.esmx and cant access to up / down migration (sinces its automated).

    Regards

    Monday, January 30, 2017 9:32 AM

Answers

All replies

  • Hi,

    You can do it by Data annotation using following code

    [DatabaseGenerated(DatabaseGenerationOption.Computed)]      
    public DateTime Created { get; set; }
    
    [DatabaseGenerated(DatabaseGenerationOption.Computed)]      
    public DateTime Updated { get; set; }


    and in Migration class

     public partial class AddedComputedColumn : DbMigration
        {
            public override void Up()
            {            
                AddColumn("dbo.TableName", "Created", c => c.DateTime(defaultValueSql: "GETDATE()"));
                AddColumn("dbo.TableName", "Updated", c => c.DateTime(defaultValueSql: "GETDATE()"));
            }
    
            public override void Down()
            {
                DropColumn("dbo.TableName", "Created");
                DropColumn("dbo.TableName", "Updated");
            }
        }

    These articles may be helpful

    http://lancelarsen.com/entity-framework-code-first-computed-getdate/

    https://andy.mehalick.com/2014/02/06/ef6-adding-a-created-datetime-column-automatically-with-code-first-migrations/

    Monday, January 30, 2017 10:28 AM
  • Hi Sandeep,

    As i have automated migration, i have no migrations classes.

    For the moment i use a solution found on the web by overriding SaveChanges... best workaround i found.

    Monday, January 30, 2017 3:31 PM
  • Hi Predalpha,

    I am glad to know that you resolve the issue and share your solution, please mark it as answer, it will be beneficial to other communities who have the similar issue.

    Best regards,

    Cole Wu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 6, 2017 9:36 AM
    Moderator