如何使用linq获取相关数据

时间:2017-03-16 22:00:36

标签: c# entity-framework linq

我希望找到一些更智能的方法来使用IQueryable获取相关的书籍描述。

IQueryable list = db.Students.Select(x => new StudentsViewModel
        {
            StudentID = x.StudentID,
            Name = x.Name,
            BookID = x.BookID,
            DescriptionForBookByBookID = db.Books.Where(v => v.BookID == x.BookID).Select(v => v.Description).FirstOrDefault().ToString()
        });

感谢您的任何建议;)

1 个答案:

答案 0 :(得分:2)

Book实体中定义Student的导航属性:

public int StudentID { get; set; }
public string Name { get; set; }
public int? BookID { get; set; } // assume book is optional, but you can use int
public virtual Book Book { get; set; }

并使用它来获取您的视图模型的书籍描述:

db.Students.Select(s => new StudentsViewModel
{
    StudentID = s.StudentID,
    Name = s.Name,
    BookID = s.BookID,
    DescriptionForBookByBookID = s.Book.Description
})

生成的查询看起来像

SELECT
    [Extent1].[StudentID] AS [StudentID],
    [Extent1].[Name] AS [Name],
    [Extent1].[BookID] AS [BookID],
    [Extent2].[Description] AS [Description]
    FROM  [dbo].[Students] AS [Extent1]
    LEFT OUTER JOIN [dbo].[Books] AS [Extent2] 
        ON [Extent1].[BookID] = [Extent2].[BookID]