简体   繁体   English

实体框架性能问题

[英]Entity Framework performance problems

I'm having a problem where the below query is taking around 700ms to execute. 我遇到以下查询需要大约700毫秒才能执行的问题。 It's in a loop and gets called 100+ times so it's taking forever. 它处于一个循环中,被调用了100多次,因此它永远存在。

Model: 模型:

public class ReleaseDates
{
    public int Id { get; set; }
    public string MovieName { get; set; }
    public string Country { get; set; }
    public DateTime ReleaseDate { get; set; }
    public string AlternateSource { get; set; }
}

Query: 查询:

public async Task<List<ReleaseDates>> GetReleaseDatesAsync(string movieName)
{
    return await Db.ReleaseDates.Where(x => x.MovieName == movieName && string.IsNullOrEmpty(x.AlternateSource)).ToListAsync();
}

Any suggestions how to speed this up? 有什么建议可以加快速度吗?

Get rid of the loop. 摆脱循环。 That's the problem. 那就是问题所在。 You're sending a lot of queries to database. 您正在向数据库发送很多查询。

Store all the movie names that you're searching for in a list and do a contains there. 将要搜索的所有电影名称存储在列表中,并在其中包含。

public async Task<List<ReleaseDates>> GetReleaseDatesAsync(List<string> movieNames)
{
    //movie names that you're searching for - movieNames

    return await Db.ReleaseDates.Where(x => movieNames.Contains(x.MovieName) && string.IsNullOrEmpty(x.AlternateSource)).ToListAsync();

}

If you want to get the release dates for "Ant Moon", "GodZippa", "SuperWan", your list will contain these strings and this is it. 如果您想获取“ Ant Moon”,“ GodZippa”,“ SuperWan”的发布日期,您的列表将包含这些字符串。

Some further reading: http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx 进一步阅读: http : //blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

Create a index on your movie name field. 在电影名称字段上创建索引。 Also, catch the query through profiler and exec it in Sql Management Studio with Show Plan enabled. 另外,通过探查器捕获查询并在启用了Show Plan的Sql Management Studio中执行它。 It will give you some insights to optimize the query performance. 它将为您提供一些见解,以优化查询性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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