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

前端 未结 3 2144
夕颜
夕颜 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<EditableBase>())
        {
            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.

    0 讨论(0)
  • 2020-12-31 14:06

    Well, you have complete control over the code for your entities. I'd imagine you would probably want to implement an IPropertyChanged like pattern to update your properties.

    0 讨论(0)
  • 2020-12-31 14:09

    Did consider the two options in this post where you do something on the setter (or constructor)?

    The default attribute solution seems a good one.

    0 讨论(0)
提交回复
热议问题