EF。根据第二个表中具有第一个FK的记录的属性,从一个表中选择记录

时间:2014-02-16 04:55:21

标签: c# linq entity-framework lambda

我有两张桌子。 BookTitles和BookAuthors。 BookTitle可以包含多个BookAuthors:

BookTitles:
- Book_Id
- BookName

BookAuthors:
- Author_Id
- AuthorName
- Book_Id

在第二个表中,Book_Id是外键。我首先使用Entity Framework,数据库。 这是BookTitles表的模型(自动创建):

public partial class BookTitles
{
    public BookTitles()
    { this.BookAuthors = new HashSet<BookAuthors>(); }

    public int Book_Id { get; set; }
    public string BookName { get; set; }

    public virtual ICollection<BookAuthors> BookAuthors { get; set; }
}

最后一个属性显示BookTitles类型的对象将包含从第二个表中检索的BookAuthors对象的列表。

问题:如何检索BookTitles记录,其中包含BookAuthors.AuthorName ==“AAA”类型的BookAuthors类型的对象?

我尝试了这个,但它不起作用:

using (var db = new BooksContext())
{
    var books =
        db.BookTitles.Where(x => x.BookAuthors.Contains(new BookAuthors() {AuthorName = "AAA"})).ToList();
}

如何使用Lambda表达式查询它,如何使用LINQ to Entities进行查询?

2 个答案:

答案 0 :(得分:3)

使用Any代替Contains

var books =
    db.BookTitles.Where(x => x.BookAuthors.Any(y => y.AuthorName == "AAA")).ToList();

或如果BookAuthor包含BookTitles的导航属性,您应该可以:

var books = 
    db.BookAuthors.FirstOrDefault(x => x.AuthorName == "AAA").BookTitles.ToList();

答案 1 :(得分:1)

尝试以下方法:

using (var db = new BooksContext())
{
    var books = from title in db.bookTitles
                from author in title.BookAuthors
                where author.AuthorName == "AAA"
                select title;             
}