为什么dapper会返回正确的count和null值?

时间:2015-09-13 03:42:54

标签: c# dapper

我想和dapper玩一下,所以创建了两个代表数据库的类和一个小的内连接查询,但无论出于何种原因,结果都是null值。我是新手,所以从我在文档中读到的内容和SO(How do I write one to many query in Dapper.Net?)上的一个很好的答案来看,我似乎正确地进行了这种设置。为什么结果计数是正确的,但值都是空的?

 con.Open();
    string query = @"select Orders.OrderID as OrderID,
                     Orders.OrderNumber as Orders_OrderNumber,
                     Product.ProductNumber as Product_ProductNumber,
                     Product.ProductID as Product_ProductID,
                     Product.OrderID as Product_OrderID
                     from Orders INNER JOIN Product ON Orders.OrderID = Product.OrderID WHERE Orders.OrderNumber LIKE '%" + orderNumber + "%'";
    dynamic data = con.Query<dynamic>(query);
    Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(Orders), new List<string> { "OrderID" });
    Slapper.AutoMapper.Configuration.AddIdentifiers(typeof(Product), new List<string> { "ProductID" });

    var orders = (Slapper.AutoMapper.MapDynamic<Orders>(data) as IEnumerable<Orders>).ToList();
    //var orders = Slapper.AutoMapper.Map<Orders>(data);
    return orders; // count is correct but values are null

类:

 public class Product
    {
        public int ProductID { get; set; }
        public int OrderID { get; set; }
        public string ProductNumber { get; set; }
    }

 public class Orders
    {
        public int OrderID { get; set; }
        public string OrderNumber { get; set; }
        public List<Product> Products { get; set; }
    }

非常感谢任何帮助。

谢谢!

3 个答案:

答案 0 :(得分:0)

我想象你的映射器没有按预期工作。进入您的映射器并确保它按预期工作。

答案 1 :(得分:0)

似乎是 Orders.OrderNumber as Orders_OrderNumber失败点。试试Orders.OrderNumber as OrderNumber

答案 2 :(得分:0)

使用Auto Mappers的最佳做法是断言语句,尤其是在动态对象映射的情况下。见example。可能会帮助您找到问题。

此外,请查看下面的Mapper源代码:

public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)
    {
        var mappedObject = default(TDestination);
        if (source != null)
        {
            var sourceType = source.GetType();
            var destinationType = typeof(TDestination);

            mappedObject = (TDestination)Map(source, sourceType, destinationType, opts);
        }
        return mappedObject;
    }

当返回Empty Collection时,它似乎会返回T的默认值。