Inserting current Database date time via Entity framework

江枫思渺然 提交于 2019-12-05 18:51:22
Gert Arnold

As the column has a default value set by the database you can simply mark the datetime column as computed:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
property DateTime Date { get; set; }

or in fluent mapping

this.Property(t => t.Date)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

in a EntityTypeConfiguration class, or

modelBuilder.Entity<MyClass>().Property(t => t.Date)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

in an OnModelCreating override.

This will cause EntityFramework to read the value of the column at each read, insert or update of a record, but it will never set it.

One way is to use UTC dateTime so in C# you can use

DateTime.UtcNow

You could also set

DateTime dateTime = new DateTime();
dateTime = SqlDateTime.MinValue.Value;

You can even create extension method :

public static class DateExtension
    {
        public static DateTime SqlValidDateTime(this DateTime d)
        {
            return SqlDateTime.MinValue.Value;
        }
    }

Also for:

If we define the datetime as null, we get an exception on the insert that the value cannot be null.

You should pass instead of null ->

DbNull.Value 

and then insert should pass.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!