GenericRepository TEntity change attribute value

倾然丶 夕夏残阳落幕 提交于 2019-12-08 13:20:57

问题


I am using EF 5.0 and the model first approach. I have build a GenericRepository that has the basic get, insert, delete etc statements. Like:

public virtual void Insert(TEntity entity)
{
      dbSet.Add(entity);
}

My EF entities all have the attributes Modified and ModifiedBy. Now I want to change this values everytime I save an entity. Is it possible to modify this two attributes (set the value) without writing an specific implementation all the time?

Thank you


回答1:


I see two options for you to do this, but they both entail either introducing a base type or an interface for all of your entities to cover them in a generic function. I would prefer an interface, although each entity would have to implement it again and again.

Let's say you create

interface IAuditable
{
    DateTime Modified { get; set; }
    string ModifiedBy {get; set; } // User id?
}

Now you can do:

public virtual void Insert(TEntity entity)
   where TEntity : IAuditable
{
     entity.Modified = DateTime.Now;
     entity.ModifiedBy = ???? // Whatever you get the name from
     ...
}

(Same for edit)

You can also subscribe to the context's SavingChanges event:

// In the constructor:
context.SavingChanges += this.context_SavingChanges;

private void context_SavingChanges(object sender, EventArgs e)
{
    foreach (var auditable in context.ObjectStateManager
        .GetObjectStateEntries(EntityState.Added | EntityState.Modified)
        .Select(entry => entry.Entity)
        .OfType<IAuditable>)
    {
        auditable.Modified = DateTime.Now;
        auditable.ModifiedBy = ????;
    }
}

If you work with DbContext you can get to the event by

((IObjectContextAdapter)this).ObjectContext.SavingChanges

I'd like to add that more reliable time tracking can (and maybe should) be achieved by database triggers. Now you depend on a client's clock.




回答2:


You can do this using the following code in your all methods of repository where you want to.

     public virtual void Edit(TEntity entity)
     {
          entity.Modified=DateTime.Now;
          entity.ModifiedBy=User.Identity.Name;
          //Other saving to repository code
     }


来源:https://stackoverflow.com/questions/14643661/genericrepository-tentity-change-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!