How to manage GetDate() with Entity Framework

前端 未结 5 1237
一生所求
一生所求 2021-02-07 03:52

I have a column like this in 1 of my database tables

DateCreated, datetime, default(GetDate()), not null

I am trying to use the Entity Framewor

5条回答
  •  生来不讨喜
    2021-02-07 04:45

    Here is a working workaround:

    1) Change the column to datetime2 as mentioned elsewhere. This fixes the conversion error.

    2) Add a trigger that sets DateCreated to getdate();

    CREATE TRIGGER [TR_AS_ChangeTime] ON [AS_ApplicationSession] 
      AFTER INSERT,UPDATE AS
    BEGIN
    
      SET NOCOUNT ON;
      UPDATE AS_ApplicationSession 
      SET AS_ChangeTime = getdate() 
      WHERE AS_Id IN(SELECT AS_ID FROM INSERTED)
    
    END
    

    3) If neccessary, set

    p.DateCreated = DateTime.MinValue;
    

    just to initialize it.

    4) If you need the DateCreated from the database, add

    context.Refresh(System.Data.Objects.RefreshMode.StoreWins, p);
    

    just after

    context.SaveChanges();
    

提交回复
热议问题