[英]Reading entity properties in generic repository
I'm writing a simple logging mechanism for my app. 我正在为我的应用程序编写一种简单的日志记录机制。
I have generic repository: 我有通用存储库:
public class GenericRepository<TEntity>:IRepository<TEntity> where TEntity : class
{
internal Equipment_TestEntities context;
internal DbSet<TEntity> dbSet;
internal Log entry;
public GenericRepository(Equipment_TestEntities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
this entry= new Log();
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
AddLog("insert "+typeof(TEntity)+" "+entity.ToString());
}
private void AddLog(string action)
{
entry.Action = action;
entry.Date = DateTime.Now;
string username = HttpContext.Current.User.Identity.Name;
username = username.Substring(username.LastIndexOf("\\") + 1);
entry.Who = 1;
context.Logs.Add(entry);
}
}
In entry.Action
I want to keep: 在
entry.Action
我要保留:
In 1) I can easily hardcone action 2) I can use TypeOf
and get entity class name 1)我可以轻松地采取行动2)我可以使用
TypeOf
并获取实体类名称
But in 3rd I have a bit problem. 但是在第三届我有一个问题。 In case of insert I can ask db for the newest record but what should I do in Edit/remove cases?
如果要插入,我可以向db请求最新记录,但是在“编辑/删除”情况下该怎么办? Is there any ways to get properties value from those entities?
有什么方法可以从这些实体获取属性值?
@Update: @Update:
sample part from unitOfWork: unitOfWork的样本部分:
public IRepository<Storage> storageRepository
{
get
{
if (this.StorageRepository == null)
{
this.StorageRepository = new GenericRepository<Storage>(context);
}
return StorageRepository;
}
}
IUnitOfWork: public interface IUnitOfWork : IDisposable { IRepository storageRepository { get; IUnitOfWork:公共接口IUnitOfWork:IDisposable {IRepository storageRepository {get; } }
}}
I'd create an interface for the entities: 我将为实体创建一个接口:
public interface IEntity
{
int? Id { get; set; }
}
Then change the generic constraint: 然后更改一般约束:
public class GenericRepository<TEntity>:IRepository<TEntity>
where TEntity : class, IEntity
{
...
}
Now you can simply use entity.Id to identify your entities.: 现在,您可以简单地使用entity.Id来标识您的实体。:
public virtual void Remove(TEntity entity)
{
if (!entity.Id.HasValue) {
throw new Exception("Cannot remove " + entity + ", it has no ID");
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.