如何在C#中的存储库中设置一些实体属性?

我有一个数据库,其所有实体都有一些用于创建/修改/删除的日志字段,我必须在我的所有CRUD操作中获取当前用户ID并设置这些字段以用于安全目的….

这是我的实体的一个例子:

//log properties public byte RecordStatus { get; set; } public string RecordStatusDescription { get; set; } public string CreatedBy { get; set; } public DateTime CreatedDateTime { get; set; } public string CreatorIPAddress { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedDateTime { get; set; } public string ModifierIPAddress { get; set; } public string RemovedBy { get; set; } public string RemovedDateTime { get; set; } public string RemoverIPAddress { get; set; } public bool IsRemoved { get; set; } 

我正在使用Repository,我想在我的IRepository接口中添加这样的东西:

 public interface IBaseRepository where TEntity : class { void Createdby(string UserId , string userIP); void ModifiedBy(string UserId , string userIP); void RemovedBy(string UserID , string userIP); } 

那么如何在我的存储库中实现它,然后在我的操作中使用它呢?

我可以用传统的方式设置这个字段,但我希望有更清晰的操作……

好吧,所以你必须制作一个清晰的IRepository并尽可能简化这样(因为你想要这个Generic):

IRepository

 public interface IRepository { void Add(T entity); void Delete(T entity); void Delete(int id); T GetById(int id); IEnumerable GetAll(); void Update(T entity); void save(); } 

并创建一个通用存储库,如下所示:

 public class Repository : IRepository where T : EntityBase { internal MyDbContext context; internal DbSet dbSet; public Repository() { context = new MyDbContext(); this.dbSet = context.Set(); } public void Add(T entity) { dbSet.Add(entity); } public void Delete(T entity) { dbSet.Remove(entity); } public void Delete(int id) { dbSet.Remove(dbSet.Find(id)); } public T GetById(int id) { return dbSet.Find(id); } public IEnumerable GetAll() { return dbSet.AsEnumerable(); } public void Update(T entity) { dbSet.Attach(entity); context.Entry(entity).State = EntityState.Modified; } public void save() { context.SaveChanges(); } } 

关于EntityBase的好处是,因为你的所有属性都有一个id,你可以很容易地这样:

 public class EntityBase { public int id { get; set; } } 

然后将其实现到您的模型

 public class Example : EntityBase { public byte RecordStatus { get; set; } public string RecordStatusDescription { get; set; } public string CreatedBy { get; set; } public DateTime CreatedDateTime { get; set; } public string CreatorIPAddress { get; set; } public string ModifiedBy { get; set; } public DateTime ModifiedDateTime { get; set; } public string ModifierIPAddress { get; set; } public string RemovedBy { get; set; } public string RemovedDateTime { get; set; } public string RemoverIPAddress { get; set; } public bool IsRemoved { get; set; } } 

使用这个简单的存储库的好处是你可以轻松地用它做任何事情,例如:

 public class HomeController : Controller { Repository _repository = new Repository(); public ActionResult Index() { vm.Example = _repository.GetAll() .Where(x => x.RecordStatusDescription == "1").ToList(); return View("index",vm); } }