有什么方法可以加快EntityFramework.Extensions.EFCore

时间:2020-01-21 10:58:39

标签: sql-server performance orm sql-update ef-core-3.1

我正在尝试加快某些系统功能。有很多对数据库的访问,而我正在减少和删除额外的访问。 (我将EFCore 3.1与SQL Server一起使用)

在一种情况下,我没有使用Z.EntityFramework.Extensions.EFCore nuget库的UpdateFromQuery方法,而不是一次一个地更新很多记录(> 10M)(使用简单的EFCore SaveChanges方法)。 这个变化,很好地提高了我的表现!但还是很慢!

我在SQL事件探查器中查看查询,是的。此函数仅生成一个查询以在数据库上执行。但是此查询未优化。查询中有一个奇怪的“连接”,会降低速度。

我的桌子:

public class Post
{
    public int Id { get; set; }
    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
    public string Name { get; set; }
    public string Content { get; set; }
    public int Type { get; set; }
}

dbcontext:

public class SampleDbContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        options.UseSqlServer("Data Source=.;Initial Catalog=Demo;Integrated Security=True");
    }
}

我如何使用UpdateFromQuery:

static void Main(string[] args)
{
    using var dbcontext = new SampleDbContext();
    dbcontext.Posts.Where(x => x.Type == 4).UpdateFromQuery(x => new Post { Type = 8 });
}

生成的查询(在SQL事件探查器中)

exec sp_executesql N'
UPDATE A 
SET A.[Type] = @zzz_BatchUpdate_0
FROM [Posts] AS A
INNER JOIN ( SELECT [p].[Id], [p].[BlogId], [p].[Content], [p].[Name], [p].[Type]
FROM [Posts] AS [p]
WHERE [p].[Type] = 4
       ) AS B ON A.[Id] = B.[Id]
',N'@zzz_BatchUpdate_0 int',@zzz_BatchUpdate_0=8

这是我的问题:

1-我如何摆脱那个JOIN ?? !!

2-是否有具有批量更新功能的库可以生成没有愚蠢联接的脚本?

(我已经知道我可以使用直接的SQL命令或SP)

非常感谢

0 个答案:

没有答案