petapoco的通用FetchDictionary方法

时间:2015-10-20 22:41:01

标签: .net generics reflection petapoco

PetaPoco有这种方法:

public List<T> Fetch<T>(string sql, params object[] args) 
    {
        return Query<T>(sql, args).ToList();
    }

我想创建一个这样的方法:

        public Dictionary<Guid, T> FetchDict<T>(string sql, params object[] args)
    {
//What goes here ?
        return Query<T>(sql, args).ToDictionary(x => ???, x => x);
    }

在上面的存根中,它应该使用反射&amp;使用PrimaryKey属性并将该字段设置为键。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

想出来:

public Dictionary<K, T> FetchDict<K,T>(string sql, params object[] args)
    {   
        Type typ = typeof(T);
        var primKey = TableInfo.FromPoco(typ).PrimaryKey;
        var prop = typ.GetProperty(primKey);
        return Query<T>(sql, args).ToDictionary(x => (K)prop.GetValue(x), x => x);
    }