实体框架在调用INSERT之前加载所有行

本文关键字:加载 框架 调用 INSERT 实体 | 更新日期: 2023-09-27 18:11:08

我有一些实体框架代码,我不认为是非常有效的。基本上,我有一个ApplicationUser类,看起来像这样:

public class ApplicationUser : IdentityUser
{
   public string CompanyName { get; set; }
   public virtual ICollection<SolverRun> Runs { get; set; }
   // .. other stuff generated by the Visual Studio template
}

我想做的是在SolverRuns中为当前用户创建一个新行:

// Log run in database
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(OwnerId);
currentUser.Runs.Add(new SolverRun
{
   Base = job.Base,
   Duration = context.JobRunTime,
   Result = (context.Result ?? "").ToString(),
   RunName = job.RunName,
   Start = context.FireTimeUtc.GetValueOrDefault().LocalDateTime
});
manager.Update(currentUser);

这个效果很好。但是,我看到的是以下查询:

exec sp_executesql N'SELECT 
    [Extent1].[SolverRunID] AS [SolverRunID], 
    [Extent1].[RunName] AS [RunName], 
    [Extent1].[Base] AS [Base], 
    [Extent1].[Start] AS [Start], 
    [Extent1].[Duration] AS [Duration], 
    [Extent1].[Result] AS [Result], 
    [Extent1].[ApplicationUser_Id] AS [ApplicationUser_Id]
    FROM [dbo].[SolverRuns] AS [Extent1]
    WHERE ([Extent1].[ApplicationUser_Id] IS NOT NULL) AND ([Extent1].[ApplicationUser_Id] = @EntityKeyValue1)',N'@EntityKeyValue1 nvarchar(128)',@EntityKeyValue1=N'029a20a9-b487-4579-87d0-50608ed7f058'

将选择该用户的SolverRuns表中的每一行。我怀疑是发生在getter对于currentUser.Runs

我担心随着用户添加越来越多的运行(最终可能有数千次),这将变得越来越慢。是否有一种方法,只是添加新行,而不是选择一切首先?谢谢!

更新:

根据下面py3r3str的回答,以下是我的新工作代码(在更改模型和迁移数据库等之后):

// Log run in database
using (var dbContext = new ApplicationDbContext())
{
   var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbContext));
   var currentUser = manager.FindById(job.OwnerId);
   dbContext.Set<SolverRun>().Add(new SolverRun
   {
      Base = job.Base,
      Duration = context.JobRunTime,
      Result = (context.Result ?? "").ToString(),
      RunName = job.RunName,
      Start = context.FireTimeUtc.GetValueOrDefault().LocalDateTime,
      ApplicationUser = currentUser
   });
   dbContext.SaveChanges();
}

它现在将运行这个INSERT语句(这是奇怪的,但我放弃了试图理解EF SQL查询,所以我会假设有人比我聪明认为这是有效的):

exec sp_executesql N'INSERT [dbo].[SolverRuns]([ApplicationUserId], [RunName], [Base], [Start], [Duration], [Result])
VALUES (@0, @1, @2, @3, @4, @5)
SELECT [SolverRunID]
FROM [dbo].[SolverRuns]
WHERE @@ROWCOUNT > 0 AND [SolverRunID] = scope_identity()',N'@0 nvarchar(128),@1 nvarchar(max) ,@2 nvarchar(max) ,@3 datetime2(7),@4 time(7),@5 nvarchar(max) ',@0=N'029a20a9-b487-4579-87d0-50608ed7f058',@1=N'PilotRun',@2=N'YUL',@3='2015-09-03 11:07:32.0353181',@4='00:00:04.1521401',@5=N'Success'

请注意,调用currentUser.Runs将惰性加载所有运行,如预期的那样。

实体框架在调用INSERT之前加载所有行

最简单的方法之一是为SolverRun实体添加外键:

class SolverRun
{
    ...
    public string ApplicationUserId { get; set; }
    [ForeignKey("ApplicationUserId")]
    public virtual ApplicationUser ApplicationUser { get; set; }
}

使用ApplicationContext:

保存SolverRun实体
var solverRun = new SolverRun
{
    Base = job.Base,
    Duration = context.JobRunTime,
    Result = (context.Result ?? "").ToString(),
    RunName = job.RunName,
    Start = context.FireTimeUtc.GetValueOrDefault().LocalDateTime,
    ApplicationUserId = OwnerId
};
dbContext.Set<SolverRun>().Add(solverRun);
dbContext.SaveChanges();

在这种情况下,EF也会在ApplicationUser.Runs中添加对象。