简体   繁体   English

显示调用 SaveChanges() 时 Entity Framework Core 为 PostgreSQL 生成的数据库查询

[英]Show database query generated by Entity Framework Core for PostgreSQL when SaveChanges() called

I have created a database first implementation of entity framework core for postgreSQL.我已经为 postgreSQL 创建了实体框架核心的数据库第一个实现。 I have tried a simple item creation and save, but am getting a syntax error.我尝试了一个简单的项目创建和保存,但出现语法错误。 I'd like to be able to see the generated SQL statement that might give me a clue as to the issue.我希望能够看到生成的 SQL 语句,这可能会给我关于这个问题的线索。 How can I enable this type of output when debugging?调试时如何启用这种类型的 output? I am new to EF in general, so for answers, please be specific and clear about the requirement.一般来说,我是 EF 的新手,所以对于答案,请具体明确要求。

Below is my test function:下面是我的测试 function:

public async Task<string> FunctionHandler(string input, ILambdaContext context)
{
    try
    {

        using (var db = new loyaltyContext())
        {
            var customer = new Customer
            {
                BusinessPartnerId = 4332482,
                StoreJoined = "chadstone",
                CreatedDateTime = DateTime.Now,
                CustomerType = "STANDARD",
                DateOfBith = DateTime.Now.Date,
                StoreJoinedDate = DateTime.Now.Date,
                UpdatedDateTime = DateTime.Now,
                FirstName = "Joe",
                LastName = "Test",
                Gender = "M",
                OrganisationName = "Australian Pharmaceutical Industries"
            };

            customer.Membership.Add(new Membership { BusinessPartnerId = 4332482, DateCreated = DateTime.Now, LoyaltyCustomerId = 1234, McaId = "2701000" });
            db.Customer.Add(customer);
            var count = db.SaveChanges();
            Console.WriteLine("${count} changes");
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    return input?.ToUpper();
}

Current error:当前错误:

Npgsql.PostgresException (0x80004005): 42601: syntax error at end of input

   at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()

--- End of stack trace from previous location where exception was thrown ---

   at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext() in C:\projects\npgsql\src\Npgsql\NpgsqlConnector.cs:line 973

--- End of stack trace from previous location where exception was thrown ---

   at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming) in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 407

   at Npgsql.NpgsqlDataReader.NextResult() in C:\projects\npgsql\src\Npgsql\NpgsqlDataReader.cs:line 298

   at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1195

   at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior behavior) in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1076

   at Npgsql.NpgsqlCommand.ExecuteReader() in C:\projects\npgsql\src\Npgsql\NpgsqlCommand.cs:line 1067

   at AWSLambdaLCSTest.Function.GetAll(NpgsqlConnection connection, String schema, String table) in C:\Users\JMatson\source\repos\AWSLambdaLCSTest\AWSLambdaLCSTest\Function.cs:line 109

   at AWSLambdaLCSTest.Function.FunctionHandler(String input, ILambdaContext context) in C:\Users\JMatson\source\repos\AWSLambdaLCSTest\AWSLambdaLCSTest\Function.cs:line 53

  Exception data:

    Severity: ERROR

    SqlState: 42601

    MessageText: syntax error at end of input

    Position: 22

    File: scan.l

    Line: 1126

    Routine: scanner_yyerror

EDIT: Updated by trying the below setting as per advice:编辑:通过按照建议尝试以下设置进行更新:

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseNpgsql("xxxxxxx").EnableSensitiveDataLogging(true);
}

However debug output still doesn't show anything:但是调试 output 仍然没有显示任何内容:

在此处输入图像描述

I wrote a blog post on this very recently.我最近写了一篇关于这个的博客文章。 Are you using .net core?您使用的是 .net 内核吗?

https://eamonkeane.dev/how-to-view-sql-generated-by-entity-framework-core-using-logging/ https://eamonkeane.dev/how-to-view-sql-generated-by-entity-framework-core-using-logging/

Enable sensitive data logging in your startup.cs class and in the ConfigureServices method.在您的 startup.cs class 和 ConfigureServices 方法中启用敏感数据日志记录。

 services.AddDbContext<DutchContext>(
            cfg =>
            {
                cfg.UseSqlServer(_config.GetConnectionString("DutchConnectionString")).EnableSensitiveDataLogging();
            }
            );

Next configure the logging level to include ef in your config file.接下来配置日志记录级别以将 ef 包含在您的配置文件中。 Usually appsettings.json通常是appsettings.json

"Logging": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
}

Now run the application and you can view the sql in your output window if you select the web server as source of the output. Now run the application and you can view the sql in your output window if you select the web server as source of the output.

output window example output window 示例

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

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