使用LEFT OUTER JOIN将SQL转换为LINQ

时间:2017-06-27 04:26:20

标签: c# sql entity-framework linq

我想知道如何将此SQL转换为LINQ ...提前感谢

DECLARE @Book table(
    BookId int,
    BookName varchar(50)
)

DECLARE @Author table(
    AuthorId int,
    AuthorName varchar(50)
)

DECLARE @Author_Book TABLE(
    --Id int IDENTITY (
    AuthorId int,
    BookId int
)

INSERT INTO @Book
(BookId,   BookName)
VALUES
( 1, 'Book1')
,( 2, 'Book2')
,( 3, 'Book3')

INSERT INTO @Author
(AuthorId,AuthorName)
VALUES
( 1, 'Author1'),
( 2, 'Author2')

INSERT INTO @Author_Book
(AuthorId,BookId)
VALUES
(1, 1)
--,(1,2)
,(1,3)
,(2,1)
,(2,2)
,(2,3)


SELECT * 
from @Book b 
left outer join @Author_Book ab 
             ON b.BookId = ab.BookId AND ab.AuthorId = 1
WHERE ab.AuthorId IS NULL

我有一个AuthorId,我必须从“Book”表中选择所有与Author_book表中的AuthorId无关的书籍...

3 个答案:

答案 0 :(得分:1)

您可以使用此查询:

var books = context.Books.Where(x => !x.Authors.Any(c => c.AuthorId == 1)).ToList();

var books = context.Books.Where(x => x.Authors.Any(c => c.AuthorId != 1)).ToList();

答案 1 :(得分:0)

public class Book
{
    public int BookId { get; set; }
    public string BookName { get; set; }
}

public class Author
{
    public int AuthorId { get; set; }
    public string AuthorName { get; set; }
}

public class Author_Book
{
    public int AuthorId { get; set; }
    public int BookId { get; set; }
}


public class Example
{
    public void Linq()
    {
        List<Book> books = new List<Book>();
        books.Add(new Book { BookId = 1, BookName = "Book1" });
        books.Add(new Book { BookId = 2, BookName = "Book2" });
        books.Add(new Book { BookId = 3, BookName = "Book3" });

        List<Author> authors = new List<Author>();
        authors.Add(new Author { AuthorId = 1, AuthorName = "Author1" });
        authors.Add(new Author { AuthorId = 2, AuthorName = "Author2" });

        List<Author_Book> bookAuthors = new List<Author_Book>();
        bookAuthors.Add(new Author_Book { AuthorId = 1, BookId = 1 });
        bookAuthors.Add(new Author_Book { AuthorId = 1, BookId = 3 });
        bookAuthors.Add(new Author_Book { AuthorId = 2, BookId = 1 });
        bookAuthors.Add(new Author_Book { AuthorId = 2, BookId = 2 });
        bookAuthors.Add(new Author_Book { AuthorId = 2, BookId = 3 });


        var selectedBooks = from b in books
                            join ba in bookAuthors on b.BookId equals ba.BookId into ab
                            from a in ab.Where(x => x.AuthorId == 1).DefaultIfEmpty()
                            where (a == null)
                            select b;
   }
}

答案 2 :(得分:0)

使用DefaultIfEmpty()在LINQ中尝试左连接。代码应如下所示: -

var a = from b in Books
    join a in Authors.Where(o => o.AuthorId == 1) on b.BookId equals a.BookId into joined
    from ba in joined.DefaultIfEmpty()
    where ba.AuthorId == null
    select b;