自定义映射Dapper.NET

时间:2013-09-19 08:28:44

标签: c# .net dapper

我可以这样做,但我认为应该有办法更好地做到这一点;

    Resource.ResourceIncrease resource = new Resource.ResourceIncrease();

    using (IDbConnection connection = OpenConnection())
    {
        dynamic reader = connection.Query<dynamic>("UserResourceGet", new { UserId = UserId }, commandType: CommandType.StoredProcedure).SingleOrDefault();
        resource.Wood.value = reader.Wood;
        resource.Wood.increase = reader.WoodIncome;

        resource.Food.value = reader.Food;
        resource.Food.increase = reader.FoodIncome;

        resource.Stone.value = reader.Stone;
        resource.Stone.increase = reader.StoneIncome;

        resource.Gold.value = reader.Gold;
        resource.Gold.increase = reader.GoldIncome;
    }
    return resource;

SQL SP&gt;

SELECT  Wood, Food, Stone, Gold, WoodIncome, FoodIncome, StoneIncome, GoldIncome
FROM Resources WHERE UserId = @UserId

类&gt;

public class Resource
{
    public int Wood { get; set; }
    public int Food { get; set; }
    public int Stone { get; set; }
    public int Gold { get; set; }
}

public class ResourceIncrease
{
    public Increase Wood{ get; set; }
    public Increase Food { get; set; }
    public Increase Stone { get; set; }
    public Increase Gold { get; set; }

    public ResourceIncrease()
    {
        this.Wood = new Increase();
        this.Food = new Increase();
        this.Stone = new Increase();
        this.Gold = new Increase();
    }
}

public class Increase
{
    public int value { get; set; }
    public int increase { get; set; }
}

1 个答案:

答案 0 :(得分:0)

我会创建一个匹配SP返回的类,然后使用AutoMapper(http://automapper.org/)将该类映射到ResourceIncrease类。

检查一下 http://geekswithblogs.net/EltonStoneman/archive/2012/01/03/mapping-and-auto-mapping-objects.aspx