Jose Jose - 1 month ago 18
C# Question

Entity Framework override SaveChanges Error


"The property 'CreateDate' on type 'Commodity' is not a primitive or
complex property. The Property method can only be used with primitive
or complex properties. Use the Reference or Collection method."


This is the POCO class I am using and this code snippets for the context

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();

}

Answer

You do not have to have the field on every table. You may not want audit tracking on all tables in that event you can inherit from a base with the audit info and override save changes accordingly. In this case inherit from 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();
}
Comments