Handling Created and Modified Date in MVC

后端 未结 1 853
小蘑菇
小蘑菇 2021-01-23 06:08

HI i have an MVC application which have CreatedDate and ModifiedDate feilds, 1. CreatedDate is when user create the module(any entry) 2. ModifiedDate is when user Edit the modu

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-23 06:52

    When i edit the module, modifiedDate and createdDate goes same

    Well, that's because in your Edit action you are specifically setting the CreatedDate, remove this line

    valpara.CreatedDate = DateTime.Now
    

    and only the ModifiedDate will be updated. However, a better approach would be to have your DB configured to set the date automatically (e.g. if you are using MSSQL set the default value to GetUtcDate()) and have EF pull that value instead of setting it client-side.

    You need to set DatabaseGeneratedOption.Identity on that particular field which tells EF that the DB will generate the value.

    FYI - you should really consider storing your dates as UTC rather than local i.e. use DateTime.UtcNow rather than DateTime.Now.


    As well as the above, in your Edit you are actually re-creating a new entry each time. If you want to modify an existing record then you need to pull that record out of the DB first e.g.

    using (MyFormDemoContext context = new MyFormDemoContext()) 
    {
        var record = context.MasterForms.SingleOrDefault(x => x.ID == id);
        if (record != null)
        {
            record.ModifyBy = 1;
            record.ModifyDate = DateTime.UtcNow;
            context.SaveChanges();
        }
    }
    

    0 讨论(0)
提交回复
热议问题