Linq-to-entities orderby gives ambiguous column name error
I've created a query in Linq-to-entities (4.0), which has me confused, as I join on a few tables, two of which share a column name (DateCreated). When I try to use orderby between the two tables with the same column name I get the following error: 'Column 'DateCreated' in order clause is ambiguous'
I'm confused as I thought specifying the table would mean it would pass that through to the SQL query. In the example below I specify 'orderby a.Datecreated', but in the TSQL it only has ORDER BY DateCreated
, when I would've expected to see ORDER BY Extent1
.DateCreated
.
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
});
}
Here is the T-SQL it creates
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
Am I missing something or doing something wrong?
P.S. It's connecting to MySQL if that makes any difference.
EDIT:
Just after I asked the question, I saw another question based on a Left Join, which led to me to write:
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);
I added the Orderby on the select new. This now works. However, I'm still confused as to why it wouldn't do the same thing when the orderby is in the main query. Hey ho! A bit annoying that I spent about 5 hours on this over a few days and within seconds of posting, I find the answer!
Have you tried to move orderby
to the end of the query after the select keyword?
Like:
actions.OrderBy(a => a.DateCreated);
It's possible the TSQL is being generated as a partial construct of your specific select new statement. Have you tried altering the name of the property to something different like:
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
}
精彩评论