开发者

Take() works with chaining only?

I have a service function to query a SQL db like so:

public IQueryable<MyModel> getAll()
{
    IQueryable<MyModel> models = (from f in db.MyModel select f);

    return models;
}

When I implement it in my controller it works when I chain the Take():

var models = myModelEntities.getAll().Take(5); 
return View(models); // returns 5 rows to the view

But like this it doesn't:

var models = myModelEnt开发者_JS百科ities.getAll();
models.Take(5); 
return View(models); // returns thousands of rows to the view

Why is Take() ignored if it's not chained? I have Lazy Loading enabled on my model...


It does work, but you're not assigning the result of Take() to anything. Take() doesn't mutate the models variable, it returns the top 5 items in the enumerable.

The following would work:

var models = myModelEntities.getAll();
models = models.Take(5); 
return View(models); // returns five rows to the view


It's because Take doesn't mutate the current IEnumerable; it returns a new one. This will work:

models = models.Take(5);


You aren't assigning the result of the second Take() call to any variable.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜