存储库模式和基本模态属性的问题



我创建了带有存储库模式和依赖项注入的.NET核心API。

这个api使用了已经存在的数据库,我已经使用脚手架生成了dbContext,问题由此开始。

  • 问题:我想处理一些来自服务层的常见列数据插入,如CreationDateTime、CreationUserId
  • 如果我们使用代码优先的方法,这非常好,因为它允许我们继承基本模态类
  • 但有了数据第一,我们将只有简单的模态

这是我的基本服务层。

public class BaseService<T> : IBaseService<T> where T : class, new()
{
private readonly IBaseRepository<T> _repository;
private readonly IUnitOfWork _unitOfWork;
public BaseService(IUnitOfWork unitOfWork, IBaseRepository<T> repository)
{
this._repository = repository;
this._unitOfWork = unitOfWork;
}
public virtual Response<T> Insert(T model)
{
// TODO: can't access this columns since T is generic
//model.CreationDateTime = DateTime.UtcNow;
//model.CreationUserId = 1;
var response = _repository.Add(model);
_unitOfWork.Commit();
return response;
}
}

到目前为止我做了什么?

我知道我可以单独访问每个服务层并在那里进行更新,如下所示。

public class SurveyRequestService : BaseService<SurveyRequest>, ISurveyRequestService
{
private readonly ISurveyRequestRepository _repository;
private readonly IUnitOfWork _unitOfWork;
public SurveyRequestService(IUnitOfWork unitOfWork, ISurveyRequestRepository repository)
: base(unitOfWork, repository)
{
this._repository = repository;
this._unitOfWork = unitOfWork;
}
public virtual Response<SurveyRequest> Insert(SurveyRequest model)
{
model.CreationDateTime = DateTime.UtcNow;
model.CreationUserId = 1;
var response = _repository.Add(model);
_unitOfWork.Commit();
return response;
}
}

如有任何帮助,我们将不胜感激。谢谢

试试这个。

class Entity: BaseEntity
{
public int Id { get; set; }
}
class BaseEntity
{
public int UserId { get; set; }
public DateTime DateTime { get; set; }
}
class Service<T> where  T : BaseEntity, new()
{
public virtual void Insert(T model)
{
model.DateTime = DateTime.Now;
model.UserId = 1;
}
}

最新更新