我有一个继承自此的类:
public abstract class BaseEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedAt { get; set; }
}
但是当我尝试使用persis实例(我没有设置CreatedAt
时)它失败并出现错误:
{"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."}
我做错了什么?
答案 0 :(得分:0)
这是因为SQL有不同的日期范围,只需添加此注释,您就可以删除错误消息:
[Column(TypeName="datetime2")]
答案 1 :(得分:0)
首先创建一个基础实体:
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; }
}
然后在您的数据库上下文中覆盖SaveChanges()
方法。
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();
}
就是这样。我从here那里取了这个例子。在那里查看更多详细信息。