实体框架覆盖SaveChanges错误

时间:2013-10-26 19:51:33

标签: c# entity-framework

  

“'Commodity'类型的属性'CreateDate'不是原始的或   复杂的财产。 Property方法只能与原语一起使用   或复杂的属性。使用参考或收集方法。“

这是我正在使用的POCO类,此代码片段用于上下文

    public class OrdNumber
{
    public int OrdNumberId { get; set; }
    public string orderNum { get; set; }
   // [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public DateTime CreateDate { get; set; }
}


        public override int SaveChanges()
    {
        DateTime saveTime = DateTime.Now;
        foreach (var entry in this.ChangeTracker.Entries().Where(e => e.State == System.Data.EntityState.Added))
        {
            if (entry.Property("CreateDate").CurrentValue == null)
                entry.Property("CreateDate").CurrentValue = saveTime;
        }
        return base.SaveChanges();

    }

1 个答案:

答案 0 :(得分:2)

您不必在每张桌子上都有该字段。您可能不希望在该事件中对所有表进行审计跟踪,您可以从具有审计信息的基础继承并相应地覆盖保存更改。在这种情况下继承自AuditInfo

public class AuditInfo
{
    [Required]
    public DateTime CreatedDateTimeUtc { get; set; }
    [Required]
    public DateTime ModifiedDateTimeUtc { get; set; }
}


public override int SaveChanges()
{
    var addedEntityList = ChangeTracker.Entries().Where(x => x.Entity is AuditInfo && x.State == EntityState.Added).ToList();
    var updatedEntityList = ChangeTracker.Entries().Where(x => x.Entity is AuditInfo && x.State == EntityState.Modified).ToList();

    if (addedEntityList.Any() || updatedEntityList.Any())
    {
        var context = HttpContext.Current;
        if (context == null)
        {
            throw new ArgumentException("Context not available");
        }

        foreach (var addedEntity in addedEntityList)
        {
            ((AuditInfo)addedEntity.Entity).CreatedDateTimeUtc = DateTime.UtcNow;
            ((AuditInfo)addedEntity.Entity).ModifiedDateTimeUtc = DateTime.UtcNow;
        }

        foreach (var updatedEntity in updatedEntityList)
        {
            ((AuditInfo)updatedEntity.Entity).ModifiedDateTimeUtc = DateTime.UtcNow;
        }
    }

    return base.SaveChanges();
}