在mvc控制器中运行EF6异步请求

时间:2014-01-03 19:52:20

标签: asp.net-mvc entity-framework asynchronous

我有mvc 5和EF6,并且之前从未真正在mvc中使用async,所以想要询问运行sql请求的最佳方法。

public ActionResult SearchTest(string id)
{
    string searchtxt = UsefulClass.ConvertObjectToString(id).Replace(",", " ").Trim();

    var model = new SearchResult();

    if (!String.IsNullOrEmpty(searchtxt))
    {

        //get the data from 3 requests
        var ArtistList = _db.Artists.SqlQuery("SELECT top 6 * FROM Artists WHERE CONTAINS(Name, N'Queen') and TopTracksStatus = 1 and GrabStatus > 1 order by playcount desc").ToList();
        var tracks = _db.Database.SqlQuery<TrackInfo>("exec SearchTracks @SearchText=N'Queen', @TopCount=10,@LengthCount=100").ToList();
        var TagsList = _db.Tags.Where(x => x.TagName.Contains(searchtxt)).Take(5).ToList();

        //work with ArtistList and add to model
        if (ArtistList.Any())
        {
            int i = 0;
            foreach (var artist in ArtistList)
            {
                i++;
                if (i == 1) //top artist
                {
                    model.BestArtist = artist;
                    model.BestArtistTrackCount = _db.TopTracks.Count(x => x.Artist_Id == artist.Id);
                }
                else
                {
                    model.ArtistList = ArtistList.Where(x => x.Id != model.BestArtist.Id);
                    break;
                }
            }
        }

        //work with tracks and add to model
        if (tracks.Any())
        {
            model.TopTrackList = tracks;
        }

        //work with tags and add to model
        if (TagsList.Any())
        {
            model.TagList = TagsList;
        }

    }
        return View(model);
}

这里我有3个请求返回ArtistList,track,TagsList,我需要将它们添加到模型然后传递给视图。如何以异步方式完成?

1 个答案:

答案 0 :(得分:0)

尝试以下示例,希望它能为您提供一个好主意。

   public async Task<ActionResult> SearchTestAsync(string id)
    {
        string searchtxt = UsefulClass.ConvertObjectToString(id).Replace(",", " ").Trim();
        var model = new SearchResult();
        if (!String.IsNullOrEmpty(searchtxt))
        {
            var art = GetArtistListResulst(model);
            var track = GetTracksResults(model);
            var tag = GetTagsListResults(model,searchtxt);
            await Task.WhenAll(art, track, tag);
        }
        return View(model);
    }


    private Task GetArtistListResulst(SearchResult model)
    {
        return Task.Run(() =>
        {
            var artistList = _db.Artists.SqlQuery("SELECT top 6 * FROM Artists WHERE CONTAINS(Name, N'Queen') and TopTracksStatus = 1 and GrabStatus > 1 order by playcount desc").ToList();
            // You don't need to use foreach because the artistList is ordered by playcount already. 
            model.BestArtist = artistList.Take(1);
            model.BestArtistTrackCount = _db.TopTracks.Count(x => x.Artist_Id == model.BestArtist.Id);
            model.ArtistList = artistList.Where(x => x.Id != model.BestArtist.Id);
        });
    }

    private Task GetTracksResults(SearchResult model)
    {
        return Task.Run(() =>
        {
            model.TopTrackList = _db.Database.SqlQuery<TrackInfo>("exec SearchTracks @SearchText=N'Queen', @TopCount=10,@LengthCount=100").ToList();
        });
    }

    private Task GetTagsListResults(SearchResult model, string searchtxt)
    {
        return Task.Run(() =>
        {
            model.TagsList = _db.Tags.Where(x => x.TagName.Contains(searchtxt)).Take(5).ToList();
        });
    }