小巧玲珑的子查询不再有效

时间:2014-10-23 17:06:07

标签: c# dapper

我正在使用dapper,我刚刚实现了splitOn函数来获取我的AdListingSearchResult中设置的位置对象,但通过这样做,我的子查询(MainPhotoFileName和TotalPhotos)现在分别为null和0。知道我在这里做错了吗?

var data = GetConnection().Query<AdListingSearchResult, AdListingLocationSearchResult, AdListingSearchResult>(@"
SELECT TOP 10 a.AdListingID, a.Title, a.Details, a.CreateDateTime, l.LocationID, l.CountryID, l.USCity, l.USStateCode, l.IntlRegion, c.CountryName,  
(SELECT TOP 1 ap.Filename FROM tbAdListingPhotos ap WHERE ap.AdListingID = a.AdListingID) AS MainPhotoFileName, 
(SELECT COUNT (*) FROM tbAdListingPhotos ap WHERE ap.AdListingID = a.AdListingID) AS TotalPhotos
FROM tbAdListing a 
INNER JOIN tbLocation l ON (a.LocationID = l.LocationID) 
INNER JOIN tbEnumCountry c ON (l.CountryID = c.CountryID) 
WHERE a.Deleted = 0  ORDER BY a.CreateDateTime DESC                 
", (a, l) =>
 {
     a.Location = l;
     return a;
 },
 splitOn: "LocationId"
 ).AsQueryable();

return data;

1 个答案:

答案 0 :(得分:2)

我猜这些子查询是为了映射到AdListingSearchResult对象上的属性。但是,行根据splitOn参数水平分区,这意味着AdListingSearchResult永远不会看到这些值。

您应该只需重新排序SQL:

SELECT TOP 10 a.AdListingID, a.Title, a.Details, a.CreateDateTime,
(SELECT TOP 1 ap.Filename FROM tbAdListingPhotos ap WHERE ap.AdListingID = a.AdListingID) AS MainPhotoFileName, 
(SELECT COUNT (*) FROM tbAdListingPhotos ap WHERE ap.AdListingID = a.AdListingID) AS TotalPhotos,
l.LocationID, l.CountryID, l.USCity, l.USStateCode, l.IntlRegion, c.CountryName
FROM tbAdListing a
...