简体   繁体   English

.Net Core控制台应用程序-EF Core SaveChangesAsync()不提交对数据库的更新

[英].Net Core Console App - EF Core SaveChangesAsync() not committing updates to database

To test the Data Access Layer of a wider project, I have written a simple console app as a test harness to call the DAL. 为了测试更广泛项目的数据访问层,我编写了一个简单的控制台应用程序作为调用DAL的测试工具。

The saving of the data is a two-step operation. 数据的保存分两步进行。 The first step is to save the very basic information from the report and HAS HAS to be succeed.. The second step is to decipher the raw data into the model and then save it but if this fails, its not a big problem and will be reported and addressed later. 第一步是从报告中保存非常基本的信息,然后HAS HAS才能成功。第二步是将原始数据解密到模型中,然后将其保存,但是如果失败,这将不是一个大问题,并且将报告并稍后处理。

The whole process is to run asynchronously (its part of a REST) but the await _context.SaveChangesAsync() calls do not appear to wait and the app exits and no data is saved. 整个过程是异步运行的(它是REST的一部分),但是await _context.SaveChangesAsync()调用似乎没有等待并且应用程序退出并且没有数据被保存。

Below is a simplified example of the DB update 以下是数据库更新的简化示例

public async Task<bool> SubmitFlightReportAsync(string ReportData)
{
    try
    {
        // Save the primary data - MUST Succeed
        _logger.LogInformation("Saving primary data database ");
        Models.MyReport myRpt = new Models.MyReport()
        {
            Status = 1,
            RawData = ReportData
        };
        _context.MyReports.Add(myRpt);

        if (await _context.SaveChangesAsync() > 0)
        {
            _logger.LogInformation("Primary save complete");

            // Now update with all the extracted data - Optional Succeed
            try
            {
                _logger.LogInformation("Extracting secondary data");
                /*
                 * 
                 * Here is where we extract all the information from the Report Data 
                 * and update the Model, before saving
                 * 
                 */
                _logger.LogInformation("Saving extracted data");

                if (await _context.SaveChangesAsync() > 0)
                {
                    _logger.LogDebug("Secondary save complete");
                }

            }
            catch (Exception ex)
            {
                _logger.LogError("Error saving secondary data ");
            }
        }
        else
        {
            _logger.LogInformation("Primary save failed");
        }
    }
    catch (Exception ex)
    {
        _logger.LogCritcal("Something went horrobly wrong");
    }
}

.and is called from the console app as such... .and从控制台应用程序中这样调用...

_logger.LogInformation("Starting application");
_fltSvc.SubmitFlightReportAsync("this is the report data as a string")
_logger.LogInformation("All done");

When I run the app, here's the logging that gets reported... 当我运行应用程序时,这是报告的日志记录...

object:Information: Starting application
object:Information: Saving primary data database

... Where's all the other logging messages?

object:Information: All done

As you can see, it gets to the point of the first SaveChangesAsync , waits a little, as if its doing something, and then jumps back to the main thread..... and NO DATA is saved in the database. 如您所见,它到达第一个SaveChangesAsync的地步,稍作等待,好像在做某件事,然后跳回主线程.....,并且没有数据存储在数据库中。

I am sure it's something pretty simple, but I just can see it... 我敢肯定这很简单,但是我可以看到...

Thanks. 谢谢。

Call SubmitFlightReportAsync in your main without await like the following. 在您的主系统中调用SubmitFlightReportAsync ,无需等待,如下所示。

public static void Main(string[] args)
{
    Task t = SubmitFlightReportAsync("bla");
    t.Wait(); //This is the line you need to have when working with console apps.
}

Asyny and Await is different while using it in Console app. 在控制台应用程序中使用Asyny和Await时有所不同。

Or take a look at the following: async at console app in C#? 还是看看以下内容: 在C#中使控制台应用程序异步?

When you call to SubmitFlightReportAsync , you initiate the execution of your operation and then return to the caller. 调用SubmitFlightReportAsync ,您将启动操作的执行,然后返回到调用方。 When you then end your application immediately, the task will not have a chance to execute. 当您立即结束应用程序时,该任务将没有机会执行。 You have to wait for task completion, before you can assume that everything is done: 您必须等待任务完成,然后才能假定一切已完成:

_logger.LogInformation("Starting application");
Task submitTask =
    Task.Run(() => _fltSvc.SubmitFlightReportAsync("this is the report data as a string"));
submitTask.Wait();
_logger.LogInformation("All done");

In case you are running this code from the Main method and you are using C# 7.0 or higher, you can also simply create an async Main and await in there: 如果您从Main方法运行此代码并且使用的是C#7.0或更高版本,则还可以简单地创建一个async Main并在其中await

static async void Main() {
    //...
    _logger.LogInformation("Starting application");
    await _fltSvc.SubmitFlightReportAsync("this is the report data as a string")
    _logger.LogInformation("All done");
    //...
}

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

相关问题 .NET 5 EF Core SaveChangesAsync 因错误而挂起 - .NET 5 EF Core SaveChangesAsync hangs on errors EF Core IdentityDbContext中的SaveChangesAsync - SaveChangesAsync in EF Core IdentityDbContext .net Core 2.2 EF:SaveChangesAsync() 将不相关的列设置为空 - .net Core 2.2 EF: SaveChangesAsync() setting unrelated columns to null 如何在 Net Core 中覆盖 SaveChangesAsync? - How to Override SaveChangesAsync in Net Core? .NET 6 控制台应用程序中的 EF Core 在 SaveChanges() 之后不会更新 - EF Core in .NET 6 console app won't update after SaveChanges() 在应用程序启动之前运行数据库迁移(.NET5、EF 核心 5) - Run database migration before app start (.NET5, EF core 5) EF Core 并在调用 SaveChangesAsync() 之前引用实体的 ID - EF Core and referencing the ID of a entity before calling SaveChangesAsync() EF Core 不会在 SaveChanges()/SaveChangesAsync() 上引发异常 - EF Core doesn't throw exceptions on SaveChanges()/SaveChangesAsync() .NET Core / EF.Core 3+ 将控制台日志记录添加到 DbContext - .NET Core / EF.Core 3+ add Console logging to DbContext 在.BeginTransaction() EF Core 3.1 中调用.SaveChangesAsync() 多少次 - How many times to call .SaveChangesAsync() in .BeginTransaction() EF Core 3.1
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM