我在 Linq-to-entities (4.0) 中创建了一个查询,这让我很困惑,因为我连接了几个表,其中两个表共享一个列名 (DateCreated)。当我尝试在具有相同列名的两个表之间使用 orderby 时,出现以下错误:“order 子句中的列 'DateCreated' 不明确”
我很困惑,因为我认为指定表意味着它将把它传递给 SQL 查询。在下面的示例中,我指定了“orderby a.Datecreated”,但在 TSQL 中,它只有 ORDER BY DateCreated
,而我本希望看到 ORDER BY Extent1
。 创建日期
。
using (PDFActionsEntities pdfEntities = new PDFActionsEntities())
{
var actions = (from a in pdfEntities.PDFActions
join f in pdfEntities.Files on a.FileID equals f.FileID into list1
from l1 in list1.DefaultIfEmpty()
join wp in pdfEntities.WebPages on a.WebPageID equals wp.webpageid into list2
from l2 in list2.DefaultIfEmpty()
orderby a.DateCreated
select new
{
ID = a.ID,
FileID = a.FileID,
WebPageID = a.WebPageID,
UserID = a.UserID,
FilePath = l1.Path,
URLPath = l2.url,
DateCreated = a.DateCreated
});
}
这是它创建的 T-SQL
SELECT
`Extent1`.`FileID`,
`Extent1`.`ID`,
`Extent1`.`WebPageID`,
`Extent1`.`UserID`,
`Extent2`.`Path`,
`Extent3`.`url`,
`Extent1`.`DateCreated`
FROM `tblpdfactions` AS `Extent1` LEFT OUTER JOIN
`tblfiles` AS `Extent2` ON `Extent1`.`FileID` = `Extent2`.`FileID` LEFT OUTER JOIN
`tblwebpageprints` AS `Extent3` ON `Extent1`.`WebPageID` = `Extent3`.`webpageid`
ORDER BY `DateCreated` ASC
我错过了什么或者做错了什么吗?
附注如果这有什么区别的话,那就是连接到 MySQL。
编辑:
就在我问这个问题之后,我看到了另一个基于Left Join的问题,这促使我写道:
var actions = (from a in pdfEntities.PDFActions
join f in pdfEntities.Files on a.FileID equals f.FileID into list1
from l1 in list1.DefaultIfEmpty()
join wp in pdfEntities.WebPages on a.WebPageID equals wp.webpageid into list2
from l2 in list2.DefaultIfEmpty()
select new
{
ID = a.ID,
FileID = a.FileID,
WebPageID = a.WebPageID,
UserID = a.UserID,
FilePath = l1.Path,
URLPath = l2.url,
DateCreated = a.DateCreated
}).OrderBy(x => x.DateCreated);
我在 select new 上添加了 Orderby。现在这有效了。但是,我仍然很困惑为什么当 orderby 在主查询中时它不会做同样的事情。嘿嘿!有点烦人的是,我在几天内花了大约 5 个小时在这个问题上,在发布后几秒钟内,我找到了答案!
最佳答案
您是否尝试过将 orderby
移至查询末尾的 select 关键字之后?
喜欢:
actions.OrderBy(a => a.DateCreated);
关于c# - Linq-to-entities orderby 给出不明确的列名错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5717326/