开发者

Select statement taking a long time

Hi I have a method like:

public JsonResult GetActivities(int id)
{
    var activities =开发者_JAVA百科 ActivityRepository.GetAll().Where(x => x.AreaId == id);

    var jsonData = new {
        rows = activities.Select(q => new {
            Id = q.Id.ToString(),
            q.Descriptor
        }).ToList()
    };

    return Json(jsonData, JsonRequestBehavior.AllowGet);
}

It works fine but I find the line:

var jsonData = new
{ 
    rows = activities.Select(q => new { Id = q.Id.ToString(), q.Descriptor }).ToList()
};

takes a very long time to execute.

Could someone please explain to me why this is and is there a more efficient way?


The problem is most likely related to your database somehow...

As @geofftnz already have mentioned, then you should use a SQL profiler (ex. AnjLab Sql Profiler), and figure out what's going on behind the scenes.

The reason for that it's not taking a long time for:

var activities = ActivityRepository.GetAll().Where(x => x.AreaId == id);

is that it's not sending any queries to the database yet, because of the return type IEnumerable<Activity> (lazy).

However when you do:

var jsonData = new 
{ 
    rows = activities.Select(q => new 
    { 
        Id = q.Id.ToString(), 
        q.Descriptor 
    }).ToList() 
};

it will make up a query, and hit the database at .ToList() (eager).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜