2014-03-12 41 views
1

我創建了以下擴展。爲泛型擴展方法創建超載

代碼

public static class QueryableExtensions 
{ 
    public static QueryMapper<TSource> Map<TSource>(this IQueryable<TSource> source) 
    { 
     return new QueryMapper<TSource>(source); 
    } 

    public static ObjectMapper<TSource> Map<TSource>(this TSource obj) 
    { 
     return new ObjectMapper<TSource>(obj); 
    } 
} 

如何調用上面

return this.repository.FindAll() 
      .OrderBy(o => o.Name) 
      .Map().To<TEntityDto>(); 

錯誤

無法隱式轉換類型 'TEntityDto' 到 'System.Collections.Generic.IEnumerable'。一個明確的 轉換不存在(是否缺少強制轉換?)

我原來的解決方案是重命名取的IQueryable輸入到「MapQuery」的方法...

,但我想在對象或集合上調用時具有相同的命名約定。我不知道如何去添加約束(或某些東西)來限制調用/源對象的外觀。 (例如單個類/集合的類)

回答

0

添加這個解決了我的問題,因爲我使用它的查詢鏈有一個命令並且生成的對象是IOrderedQueryable,而不是IQueryable。

public static QueryMapper<TSource> Map<TSource>(this IOrderedQueryable<TSource> source) 
{ 
    return new QueryMapper<TSource>(source); 
} 

作爲最後的想法...

我只是想知道爲什麼會 「地圖(這個TSource OBJ)」,有超過 「地圖(這個IQueryable的源)」 的偏好,如IOrderedQueryable有一個基本類型的IQueryable?

的話題

Generics and calling overloaded method from difference class - precedence issue

一些更多的信息