简体   繁体   English

EF Core 2.1中的DbContext.Database.EnsureCreate令人困惑的行为

[英]Confusing Behavior of DbContext.Database.EnsureCreated in EF Core 2.1

I am developing some code based on the tutorial found at https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/intro?view=aspnetcore-2.1&tabs=visual-studio . 我正在根据位于https://docs.microsoft.com/zh-cn/aspnet/core/data/ef-rp/intro?view=aspnetcore-2.1&tabs=visual-studio的教程开发一些代码。 Specifically, I am looking at the following snippet in the file Program.cs. 具体来说,我正在查看文件Program.cs中的以下片段。

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;

        try
        {
            var context = services.GetRequiredService<SchoolContext>();
            context.Database.EnsureCreated();
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred creating the DB.");
        }
    }

    host.Run();
}

I am using the Contoso University data model as presented in the tutorial with a ConnectionString defined in the appSettings.json file using localdb. 我正在使用本教程中介绍的Contoso University数据模型,并使用localdb在appSettings.json文件中定义了ConnectionString。 I modified the code as follows: 我将代码修改如下:

public static void Main(string[] args)
{
    var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        bool dbCreated = false;
        var services = scope.ServiceProvider;

        try
        {
            var context = services.GetRequiredService<SchoolContext>();
            dbCreated = context.Database.EnsureCreated();
            if (dbCreated) DbInitializer.Initialize(context);
        } // end try
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred creating the DB.");
        } // end catch (Exception ex)

    } // end using (var scope = host.Services.CreateScope())

    host.Run();
} // end public static void Main(string[] args)

The behavior I observe concerns the variable, dbCreated, initialized to false. 我观察到的行为与变量dbCreated初始化为false有关。 If the database is not there, it is created and the EnsureCreated call returns true. 如果数据库不存在,则会创建该数据库,并确保SecureCreated调用返回true。 If it exists, is unchanged(false). 如果存在,则保持不变(假)。 I did not expect this behavior. 我没想到这种行为。 I would expect the call would return true, if the database already exists or if it was successfully created. 如果数据库已经存在或成功创建,我希望该调用将返回true。 If the creation fails it would return false or throw an exception or both. 如果创建失败,它将返回false或引发异常或同时发生这两种情况。 In EF5 there was a call, context.Database.Exists(). 在EF5中,有一个调用context.Database.Exists()。 See Entity Framework Code First check Database exist . 请参阅实体框架代码,首先检查数据库是否存在 This does not seem to be available in EF Core 2.1. EF Core 2.1中似乎不提供此功能。 I have two questions: 我有两个问题:

  1. How does one check for database existence in EF Core 2.1? 如何检查EF Core 2.1中数据库的存在?

  2. Is it safe to assume that the database exists after calling EnsureCreated without checking the return value? 是否可以安全地假设在调用SecureCreated之后不检查返回值就存在数据库?

I would expect the call would return true, if the database already exists or if it was >successfully created. 如果数据库已经存在或成功创建,我希望调用将返回true。

. . .

If the creation fails it would return false or throw an exception or both. 如果创建失败,它将返回false或引发异常或同时发生这两种情况。

That would violate .NET API Design Guidelines: 这将违反.NET API设计指南:

X DO NOT return error codes. X不返回错误代码。
Exceptions are the primary means of reporting errors in frameworks. 异常是报告框架中的错误的主要方法。
✓ DO report execution failures by throwing exceptions. ✓通过抛出异常来报告执行失败。

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing

Is it safe to assume that the database exists after calling EnsureCreated without checking the return value? 是否可以安全地假设在调用SecureCreated之后不检查返回值就存在数据库?

Yes. 是。

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

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