我正在尝试使用带有 JOIN 的 LINQ 查询(在 VB.NET 中)返回单个实体类(“类别”),但它不起作用。我认为要么是因为:
- 我得到一个 IEnumerable 结果集(1 个)或
我得到的不仅仅是加入中的第一个表的列
因为我得到了这个无效的类型转换异常:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[category]'
to type 'category'.
这是我想要的 SQL(注意我不想要连接表中的任何列):
select subcat.*
From category as cat
join category as parentcat On cat.cat_id = cat.parent_cat_id
Where parentcat.cat_url = 'dogs'
And cat.cat_url = 'poodles'
这是我在 LINQPad 中工作的 LINQ 代码:
dim q = From cat In categories _
Join parentcat In categories On parentcat.cat_id Equals cat.parent_cat_id _
Where parentcat.cat_url.ToLower = "dogs" _
And cat.cat_url.ToLower = "poodles" _
Select categories.SingleOrDefault(function(c) c.cat_id = cat.cat_id)
q.dumb
但这在 VB.NET 中的“CategoryRepository”函数中不起作用:
Public Function GetCategoryByURL(ByVal strCatURL As String, ByVal strSubCatURL As String) As category Implements ICategoryRepository.GetCategoryByURL
Return From cat In db.categories _
Join parentcat In db.categories On parentcat.cat_id Equals cat.parent_cat_id _
Where parentcat.cat_url.ToLower = strCatURL.ToLower _
And cat.cat_url.ToLower = strSubCatURL.ToLower _
Select db.categories.SingleOrDefault(Function(C) C.cat_id = cat.cat_id)
End Function
如何使它返回“类别”类的单个实例?(我需要这种方式,因为我重载了返回单个实例的相同函数......并且有效!)我已经验证数据库是正确的,它应该返回“贵宾犬”类别。
我是 LINQ 的新手,所以我确信我做错了一些非常明显的事情,所以我很感激任何帮助!