使用ValueInjecter展平包含可空类型的对象

Roc*_*lan 4 c# automapper valueinjecter

我正在尝试使用ValueInjector来压缩一个类,并让它同时复制值Nullable<int>'sint的.

例如,给出以下(人为)课程:

class CustomerObject
{
    public int CustomerID { get; set; }
    public string CustomerName { get; set; }
    public OrderObject OrderOne { get; set; }
}

class OrderObject
{
    public int OrderID { get; set; }
    public string OrderName { get; set; }
}

class CustomerDTO
{
    public int? CustomerID { get; set; }
    public string CustomerName { get; set; }
    public int? OrderOneOrderID { get; set; }
    public string OrderOneOrderName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我想将CustomerObject的一个实例展平为CustomerDTO,忽略了CustomerID和OrderID属于不同类型的事实(一个是可空的,而不是一个可空).

所以我想这样做:

CustomerObject co = new CustomerObject() { CustomerID = 1, CustomerName = "John Smith" };
co.OrderOne = new OrderObject() { OrderID = 2, OrderName = "test order" };

CustomerDTO customer = new CustomerDTO();
customer.InjectFrom<>(co);
Run Code Online (Sandbox Code Playgroud)

然后填充所有属性,具体为:

customer.CustomerID 
customer.OrderOneOrderID 
customer.OrderOneOrderName
Run Code Online (Sandbox Code Playgroud)

我意识到我可以FlatLoopValueInjection用来展平对象,我正在使用这个NullableInjection类:

public class NullableInjection : ConventionInjection
{
    protected override bool Match(ConventionInfo c)
    {
        return c.SourceProp.Name == c.TargetProp.Name &&
                (c.SourceProp.Type == c.TargetProp.Type
                || c.SourceProp.Type == Nullable.GetUnderlyingType(c.TargetProp.Type)
                || (Nullable.GetUnderlyingType(c.SourceProp.Type) == c.TargetProp.Type
                        && c.SourceProp.Value != null)
                );
    }

    protected override object SetValue(ConventionInfo c)
    {
        return c.SourceProp.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)

基本上我想把两者结合起来.这可能吗?

Omu*_*Omu 9

你可以通过覆盖TypesMatch方法来做到这一点:

    public class MyFlatInj : FlatLoopValueInjection
    {
        protected override bool TypesMatch(Type sourceType, Type targetType)
        {
            var snt = Nullable.GetUnderlyingType(sourceType);
            var tnt = Nullable.GetUnderlyingType(targetType);

            return sourceType == targetType
                   || sourceType == tnt
                   || targetType == snt
                   || snt == tnt;
        }
    }
Run Code Online (Sandbox Code Playgroud)

或者从源代码中获取FlatLoopValueInjection并根据需要进行编辑(大约10行)