开发者

Trouble converting a bit of TSQL to LINQ to Entities

Sorry about the vague title, not sure what verbage I should be using. I have a query similar to this (re-worked to save space):

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

I tried to re-write it as such:

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

but got the following error:

    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'.

I can re-write the LINQ to make it work by just joining the tables, as I would in SQL, but I thought I could accomplish what I want to do by their relationships - I'm just a bit confused why I can get publisher.Authors, but not author.Books.


Check that you have a relationship in your DB from Authors to Books.


Try this...

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();

i don't know exact relationship of the tables but you can an idea from this one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜