How can I add default values to a property when saving using Code First EF4.1?

前端 未结 3 2166
夕颜
夕颜 2020-12-31 13:22

I started by creating some models like this:

public abstract class EditableBase
{
    public DateTime CreatedOn { get; set; }
    public DateTime ModifiedOn          


        
3条回答
  •  执念已碎
    2020-12-31 14:04

    Override SaveChanges in your derived DbContext:

    public override int SaveChanges()
    {
        foreach(var entry in ChangeTracker.Entries())
        {
            var entity = entry.Entity;
            if (entry.State == EntityState.Added)
            {
                entity.CreatedOn = ...;
                entity.CreatedBy = ...;
            }
            else if (entry.State == EntityState.Modified)
            {
                entity.ModifiedOn = ...;
                entity.ModifiedBy = ...;
            }
        }
    
        return base.SaveChanges();
    }
    

    I'm only not sure if generic Entries will work directly with your base type becasue it is not actually mapped as base entity. There is also non generic version so you can rewrite it to more complex linq query or test each entry's entity type in loop.

提交回复
热议问题