Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code First computing Modified and Created properties

Given the following class, is there a way to calculate the Created and Modified properties of an entity automatically in EF Code first?

public class BaseEntity
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Timestamp]
    public byte[] RowVersion { get; set; }

    public DateTime Created { get; set; }
    public DateTime Modified { get; set; }
}

Can it be done by Attributes?

like image 428
Darbio Avatar asked Feb 18 '26 07:02

Darbio


1 Answers

I use a repository pattern for this purpose in EF.

A POCO might implement

public interface IFQuickAudit {
    Nullable<DateTimeOffset> CreatedOn { get; set; }
    Nullable<long> CreatedBy { get; set; }
    Nullable<DateTimeOffset> ChangedOn { get; set; }
    Nullable<long> ChangedBy { get; set; }
}

if it does the base respository checks this during Add or CHange methods and sets the values

public class RepositoryBase<TPoco>
//...
public virtual OperationResult Add(TPoco poco)
var entityQA = poco as IFQuickAudit;
        if (entityQA != null) {
             entityQA .CreatedBy = userId;
             entityQA .CreatedOn = when;
        }

// checks...
Context.Set<TPoco>().Add(poco);

// similar for Chnage routine
like image 174
phil soady Avatar answered Feb 20 '26 21:02

phil soady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!