无法将一些TSQL转换为LINQ到实体

时间:2010-08-12 00:20:34

标签: c# linq linq-to-entities

对于模糊的标题感到抱歉,不知道我应该使用什么verbage。我有一个类似于此的查询(重新工作以节省空间):

SELECT
    *
FROM
    Publishers p
    INNER JOIN Authors a
        ON p.AuthorID = a.AuthorID
    INNER JOIN Books b
        ON a.BookID = b.BookID
WHERE
    p.PublisherName = 'Foo'
ORDER BY
    b.PublicationDate DESC

我试图重写它:

var query =
    from publisher in ctx.Publishers
    from author in publisher.Authors
    from books in author.Books
    ...

但出现以下错误:

    Error   1   An expression of type 'Models.Books' is not allowed in a 
    subsequent from clause in a query expression with source type
    'System.Linq.IQueryable<AnonymousType#1>'.  Type inference failed in the
    call to 'SelectMany'.

我可以通过加入表来重新编写LINQ来使其工作,就像在SQL中一样,但我认为我可以通过他们的关系完成我想要做的事情 - 我只是有点困惑为什么我可以获得publisher.Authors,但不是author.Books。

2 个答案:

答案 0 :(得分:0)

检查您的数据库中是否存在从作者到图书的关系。

答案 1 :(得分:0)

试试这个......

var result = (from pItem in ctx.Publishers
join aItem in ctx.Authors on pItem.AuthorId equals aItem.AuthorId
join bItem in ctx.Books on pItem.BookId equals bItem.BookId
where pItem.PublisherName== "Foo"
select new {
// Fields you want to select
 }
).ToList();

我不知道表格的确切关系,但你可以从这一个想法。