Entity Framework Core is slow - how do I make it faster?

c# database entity-framework-core postgresql

Question

Retrieve records from database and assign it to an object.

private readonly ApplicationDbContext _context;
var itemsData = _context.Items;

for (int i = 0; i < itemsData.Count(); i++)
{
    _Response.Items.Add(new Models.Items
        {
            Name = itemsData.ToList()[i].Name,
            ....
            Created = (DateTime)itemsData.ToList()[i].Created,
            Updated = (DateTime)itemsData.ToList()[i].Updated
        });
}

Note: There are less than 1000 records and already it's noticeability slow.

1
2
3/30/2017 2:52:10 AM

Accepted Answer

You are calling ToList on every iteration, which executes the SQL query against the database every time. Do this 1000 times and no wonder it's slow.

Just call ToList once and then foreach the result:

var itemsData = _context.Items.ToList();

foreach (var item in itemsData)
{
    _Response.Items.Add(new Models.Items
    {
        Name = item .Name,
        ....
        Created = (DateTime)item.Created,
        Updated = (DateTime)item.Updated
    });
}
6
3/30/2017 2:49:57 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow