这是我的视图模型。
public class ProductViewModel
{
public Guid Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public bool IsAvailable { get; set; }
}
从客户发布表单时,表单将提交给此控制器
public async Task<IHttpActionResult> AddProduct(ProductViewModel productViewModel)
{
await ServiceInstances.PostAsync("product/add", productViewModel);
return Ok();
}
然后该控制器将表单提交给API控制器
这是我单独的项目。
[HttpPost]
[Route("add")]
public IHttpActionResult AddProduct(ProductViewModel model)
{
_productService.AddProduct(model.UserServiceDetails());
return Ok();
}
分机UserServiceDetails
我在哪里获得登录用户信息
public static UserServiceDetailModel<T> UserServiceDetails<T>(this T model)
{
var serviceRequestModel = new ServiceRequestModel<T>()
{
Model = model,
LoginInfo = HttpContext.Current.User.Identity.GetUserLoginInfo();
};
}
AddProductService:
public void AddProduct(UserServiceDetailModel<ProductViewModel> serviceRequestModel)
{
var repo = _genericUnitOfWork.GetRepository<Product, Guid>();
var mapped = _mapper.Map<ProductViewModel, Product>(serviceRequestModel.Model);
mapped.Id = Guid.NewGuid();
mapped.CreatedDate = GeneralService.CurrentDate();
mapped.CreatedById = serviceRequestModel.LoginInfo.UserId;
repo.Add(mapped);
_genericUnitOfWork.SaveChanges();
}
现在我的问题是,在将该值发布到服务之前,有没有办法将值分配给此字段CreatedDate
和CreatedById
?
将这些逻辑简化为mapper:
mapped.CreatedDate = GeneralService.CurrentDate();
mapped.CreatedById = serviceRequestModel.LoginInfo.UserId;
或者有什么方法可以在
时将这些字段映射到Product
var mapped = _mapper.Map<ProductViewModel, Product>(serviceRequestModel.Model);
有时我可能在视图模型上有List<T>
,我必须使用循环添加此字段。
因此,同样的映射可能会在Add Method
或Update
上反复重复。
在某些实体中,我还必须分配ModifiedDate
和ModifiedById
。
我的Mapper配置:
public class ProductMapper : Profile
{
public ProductMapper()
{
CreateMap<ProductViewModel, Product>();
}
}
我无法在ApplicationDbContext
中将Enitity添加为IAuditableEntity和Overrride,因为我的DbContext位于单独的Project中,我无法访问Identity。