我在每个表上都有几个属性,如 CreatedDate、ModifiedDate、VersionNo。每次修改实体时,我都需要更改/添加这些属性的值。我想我可以用这些属性创建一个基类,让实体从这个基类派生,在基于 ObjectState 的 SavingChanges 期间我可以更改值和保存,这样我的审计条目将与实体隔离,事情将是抽象的。但是由于我是 Entity Framework 的新手,我发现很难理解我将如何处理映射等。
如果有人可以提出实现这一点的想法,那将非常有帮助。存储库代码如下:
public class GeneralRepository<T> : IRepository<T> where T : class
{
private ObjectSet<T> _set;
private ObjectContext _context;
public GeneralRepository(ObjectContext context)
{
if (context == null) throw new ArgumentNullException("context");
_context = context; // sets the context
_set = context.CreateObjectSet<T>(); // returns the Object Set
}
#region Methods to override to work with ObjectGraphs .
/// <summary>
/// To insert data from entity into a table.
/// </summary>
/// <param name="entity"></param>
public virtual void Insert(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_set.AddObject(entity);
}
/// <summary>
/// To delete entity from a table.
/// </summary>
/// <param name="entity"></param>
public virtual void Delete(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_set.Attach(entity);
_set.DeleteObject(entity);
}
/// <summary>
/// To update Entity into the table
/// </summary>
/// <param name="entity"></param>
public virtual void Update(T entity)
{
if (entity == null) throw new ArgumentNullException("entity");
_set.Attach(entity);
_context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
/// <summary>
/// To get th entire table contents
/// </summary>
/// <returns></returns>
public IQueryable<T> GetAll()
{
return _set;
}
}