简体   繁体   中英

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

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.

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
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM