简体   繁体   中英

Autogenerate timestamp in EF 6 (Code first): conversion of a datetime2 data type to a datetime data is an out-of-range value

I have a class inherited from this:

 public abstract class BaseEntity 
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }


    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CreatedAt { get; set; }
}

But when I try to persis instance (where I do not set CreatedAt ) it fails with error:

{"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.\r\nThe statement has been terminated."}

What I'm doing wrong?

First create a base entity:

public class Student: BaseEntity
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public DateTime? DateOfBirth { get; set; }
    public decimal Height { get; set; }
    public float Weight { get; set; }
}

public class BaseEntity{ 
    public DateTime CreatedDate { get; set; }
    public DateTime UpdatedDate { get; set; }    
}

Then in your db context override the SaveChanges() method.

public override int SaveChanges()
{
    var entries = ChangeTracker
        .Entries()
        .Where(e => e.Entity is BaseEntity && (
                e.State == EntityState.Added
                || e.State == EntityState.Modified));

    foreach (var entityEntry in entries)
    {
        ((BaseEntity)entityEntry.Entity).UpdatedDate = DateTime.Now;

        if (entityEntry.State == EntityState.Added)
        {
            ((BaseEntity)entityEntry.Entity).CreatedDate = DateTime.Now;
        }
    }

    return base.SaveChanges();
}

That's it. I have taken this example from here . Have a look there for more details.

这是因为 SQL 有不同的日期范围,只需添加此注释,您将摆脱错误消息:

[Column(TypeName="datetime2")]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM