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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With