Linq-to-entities orderby给出了不明确的列名错误

时间:2011-04-19 13:43:55

标签: c# mysql entity-framework linq-to-entities

我在Linq-to-entities(4.0)中创建了一个查询,让我感到困惑,因为我加入了几个表,其中两个共享一个列名(DateCreated)。当我尝试在具有相同列名的两个表之间使用orderby时,我得到以下错误:'order'DateCreated'在order子句中是不明确的'

我很困惑,因为我认为指定表意味着它会将其传递给SQL查询。在下面的示例中,我指定'orderby a.Datecreated',但在TSQL中它只有ORDER BY DateCreated,当我希望看到ORDER BY Extent1DateCreated时。

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

我错过了什么或做错了什么?

P.S。如果这有任何区别,它就连接到MySQL。


编辑:

在我提出问题之后,我看到另一个基于左连接的问题,这导致我写道:

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个小时,在发布的几秒钟内,我找到了答案!

2 个答案:

答案 0 :(得分:3)

您是否尝试将orderby移至select关键字后的查询末尾? 像:

actions.OrderBy(a => a.DateCreated);

答案 1 :(得分:0)

有可能将TSQL生成为特定select新语句的部分构造。您是否尝试将属性的名称更改为不同的名称:

select new
{
    ID = a.ID,
    FileID = a.FileID,
    WebPageID = a.WebPageID,
    UserID = a.UserID,
    FilePath = l1.Path,
    URLPath = l2.url,
    Created = a.DateCreated  // Change is here
}