繁体   English   中英

通用类可启动我的一些审核属性

[英]Generic Class to initiate few of my audit properties

我必须时不时地在m个方法中映射一些审计属性,因此,我编写了以下通用方法。

private static T MapAuditFields<T>(long id , bool isNew ) where T : new()
{
    dynamic result = new T();
    if (isNew)
    {
        result.xxxxxx = DateTimeHelper.GetCurrentUTCDateTime();
        result.xxxxxx = DateTimeHelper.GetCurrentUTCDateTime();
        result.xx= id;
        result.xx= id;
    }
    else
    {
        result.xxxxx= id;
        result.xxxxxx= DateTimeHelper.GetCurrentUTCDateTime();
    }
    return (T)result;
}

但是每个实例都给我一个新对象。 因此,在使用自动Mapper进行efcore映射时,我进行了两次映射。

有人能帮我避免这里的映射吗?

例如:

public bool Save(Request request)
{
   var ob = MapAuditFields<Request>(3 , true); // Getting the audit fields // Creates a new request object
  _mapper.Map<Entity>(request);  // Mapping request body with entity 

}

在此先感谢您的投入。 对不起,如果我不清楚

MapAuditFields方法可以通过反射实现。 还请记住,对象类型T必须存在idxxxxxx属性。

private static T MapAuditFields<T>(T requestObj, long id , bool isNew )
{

    if (isNew)
    {
        typeof(T).GetProperty("id").SetValue(request, DateTimeHelper.GetCurrentUTCDateTime());
        typeof(T).GetProperty("xxxxx").SetValue(request, DateTimeHelper.GetCurrentUTCDateTime());

        ...
    }
    else
    {
        typeof(T).GetProperty("id").SetValue(request, DateTimeHelper.GetCurrentUTCDateTime());
        typeof(T).GetProperty("xxxxxx").SetValue(request, DateTimeHelper.GetCurrentUTCDateTime());
    }

    return (T)result;
}

我建议您有基础对象。 在这种情况下,

private static T MapAuditFields<T>(T requestObj, long id , bool isNew ) where T : MyBaseObject
{

    if (isNew)
    {
        requestObj.id = id;
        requestObj.xxxxx = DateTimeHelper.GetCurrentUTCDateTime()

......

您还可以使用Automapper进行映射

public class SetTimestampMappingAction: IMappingAction<object, MyBaseObject>
{
    public SetTraceIdentifierAction(/*if you are using dependency injection use it here*/)
    {

    }

    public void Process(SomeModel source, SomeOtherModel destination, ResolutionContext context)
    {
        destination.xxxxxx = DateTimeHelper.GetCurrentUTCDateTime()

    }
}

public class SomeProfile : Profile
{
    public SomeProfile()
    {
        CreateMap<object, MyBaseObject>()
            .AfterMap<SetTimestampMappingAction>();
    }
}

传递我要映射审核字段的对象已作为参数传递以避免新实例解决了我的问题。 这将返回具有填充值的同一对象。

private static T MapAuditFields<T>(long id , bool isNew, T t ) where T : new()
{
    dynamic result = t;
    if (isNew)
    {
        result.xxxxxx = DateTimeHelper.GetCurrentUTCDateTime();
        result.xxxxxx = DateTimeHelper.GetCurrentUTCDateTime();
        result.xx= id;
        result.xx= id;
    }
    else
    {
        result.xxxxx= id;
        result.xxxxxx= DateTimeHelper.GetCurrentUTCDateTime();
    }
    return (T)result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM