c# - 使用 ValueInjecter 扁平化对象,包括可空类型

标签 c# automapper valueinjecter

我正在尝试使用 ValueInjector 来展平一个类,并让它也复制来自 Nullable<int>'s 的值至 int的。

例如给定以下(人为的)类:

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; }
}

我想将 CustomerObject 的一个实例扁平化为 一个 CustomerDTO,它忽略了 CustomerID 和 OrderID 的类型不同(一种可以为 null,一种不可以)。

所以我想这样做:

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);

然后填充所有属性,特别是:

customer.CustomerID 
customer.OrderOneOrderID 
customer.OrderOneOrderName

我意识到我可以使用 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;
    }
}

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

最佳答案

您可以通过覆盖 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;
        }
    }

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

关于c# - 使用 ValueInjecter 扁平化对象,包括可空类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10167447/

相关文章:

c# - 创建一个 C# 服务来监视无限循环中的变化

c# - WPF,可能是色带控件 : Adding icon to title bar

c# - 显示枚举描述而不是名称

c# - 为什么 AutoMapperExtension 的行为与直接实现不同?

c# - 从 IDataReader 映射时,我可以将 AutoMapper 配置为从自定义列名读取吗?

asp.net-mvc - 我是否必须在 Nhibernate 中的 SaveOrUpdate 之前加载/获取实体?

c# - ICollectionView 抛出 Entity Framework 附加异常

c# - 使用 Sitecore 8 内容搜索 API 的复杂查询

dependency-injection - 使用 ITypeConverter 进行 AutoMapper 依赖注入(inject)

c# - ASP.NET MVC - 使用 Automapper 进行映射