.SingleOrDefaultAsync查询结果选择顶部(2)

时间:2014-07-03 15:02:49

标签: asp.net asp.net-web-api

我开始学习Web API,我正在通过Microsoft“使用Web Api 2和Entity FrameWork 6”。如图所示http://www.asp.net/web-api/overview/creating-web-apis/using-web-api-with-entity-framework/part-5

我试图了解await和.SingleOrDefaultAsyn是如何工作的。

在BooksController中,GetBook(int id),如果我使用

var book = await db.Books.Include(b => b.Author)
                 .Where(b => b.Id == id)
                 .Select(b => new BookDetailDTO()
                  {
                     Id = id,
                     Title = b.Title,
                     Price = b.Price,
                     AuthorName = b.Author.Name,
                     Genre = b.Genre,
                     Year = b.Year
                  }).SingleOrDefaultAsync();
从输出窗口

显示

SELECT 
    [Limit1].[Id] AS [Id], 
    [Limit1].[C1] AS [C1], 
    [Limit1].[Title] AS [Title], 
    [Limit1].[Price] AS [Price], 
    [Limit1].[Name] AS [Name], 
    [Limit1].[Genre] AS [Genre], 
    [Limit1].[Year] AS [Year]
    FROM ( SELECT TOP (2) 
        [Extent1].[Id] AS [Id], 
        [Extent1].[Title] AS [Title], 
        [Extent1].[Year] AS [Year], 
        [Extent1].[Price] AS [Price], 
        [Extent1].[Genre] AS [Genre], 
        [Extent2].[Name] AS [Name], 
        @p__linq__1 AS [C1]
        FROM  [dbo].[Books] AS [Extent1]
        INNER JOIN [dbo].[Authors] AS [Extent2] ON [Extent1].[AuthorId] = [Extent2].[Id]
        WHERE ([Extent1].[Id] = @p__linq__0) AND (@p__linq__0 IS NOT NULL)
    )  AS [Limit1]

但如果我使用上述网站上的示例中的代码,那就是

 var book = await db.Books.Include(b => b.Author).Select(b => new BookDetailDTO()
                                {
                                    Id = b.Id,
                                    Title = b.Title,
                                    Price = b.Price,
                                    AuthorName = b.Author.Name,
                                    Genre = b.Genre,
                                    Year = b.Year
                                }).SingleOrDefaultAsync(b => b.Id == id);

我得到以下内容:

SELECT TOP (2) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Title] AS [Title], 
    [Extent1].[Price] AS [Price], 
    [Extent2].[Name] AS [Name], 
    [Extent1].[Genre] AS [Genre], 
    [Extent1].[Year] AS [Year]
    FROM  [dbo].[Books] AS [Extent1]
    INNER JOIN [dbo].[Authors] AS [Extent2] ON [Extent1].[AuthorId] = [Extent2].[Id]
    WHERE ([Extent1].[Id] = @p__linq__0) AND (@p__linq__0 IS NOT NULL)

我的问题是:

  1. 为什么EF使用SELECT TOP(2)?我以为SingleOrDefaultAsync只返回一个元素或null?

  2. 哪个代码在效率和优选方法方面更好?

1 个答案:

答案 0 :(得分:1)

  
      
  1. 为什么EF使用SELECT TOP(2)?我以为SingleOrDefaultAsync只返回一个元素或null?
  2.   

如果找到多个项目,SingleSingleOrDefault会抛出异常。这可以通过SELECT TOP (2)来确定,如果返回两条记录,则意味着某些事情是错误的,它将抛出异常。

  
      
  1. 哪个代码在效率和优选方法方面更好?
  2.   

你必须使用Stopwatch衡量他们的执行情况,我不认为会有太大的不同。