0

“'Commodity' 类型的属性 'CreateDate' 不是原始或复杂属性。Property 方法只能与原始或复杂属性一起使用。请使用 Reference 或 Collection 方法。”

这是我正在使用的 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();

    }
4

1 回答 1

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();
}
于 2016-10-28T21:27:59.610 回答