Adding CreatedDate to an entity using Entity Framework 5 Code First

后端 未结 7 507
心在旅途
心在旅途 2020-12-13 02:24

I am trying to add a CreatedDate property to entities in my Model and am using EF5 Code First. I want this date to not be changed once set, I want it to be a UT

7条回答
  •  粉色の甜心
    2020-12-13 03:07

    Ok so the primary issue here was that CreatedDate was being Updated every time I called SaveChanges and since I wasn't passing CreatedDate to my views it was being updated to NULL or MinDate by Entity Framework.

    The solution was simple, knowing that I only need to set the CreatedDate when EntityState.Added, I just set my entity.CreatedDate.IsModified = false before doing any work in my SaveChanges override, that way I ignored changes from Updates and if it was an Add the CreatedDate would be set a few lines later.

提交回复
热议问题