来自Entity Framework的无法捕获的错误

时间:2018-05-07 10:36:20

标签: c# sql sql-server entity-framework entity-framework-6

我正在尝试使用 Code First 方法和外部数据库实现Entity Framework的基本示例。我只想从我的数据库中的表中读取一些已存在的数据。我实现它的方式是有效的,因为它显示了正确的输出,但它在此过程中抛出了一堆异常。我找到了代码行,在此期间抛出了异常,但是我无法使用try / catch来捕获它们(参见代码)。

这是我运行程序时输出日志(调试)的屏幕转储(我用粉红色突出显示了最终输出): enter image description here

这是我要连接的表的屏幕转储: enter image description here

即使输出正确,错误似乎也会影响性能。即使表只包含六列和三行,运行代码需要2-3秒。

我做错了什么,让它表现得像这样?

CODE

使用EF连接的功能:

public PrintFirstEmployeeName()
{
    try
    {
        UniContext db = new UniContext();

        // Exceptions are thrown during this line of code:
        string fullName = db.Employees.FirstOrDefault().first_name 
                  + " " + db.Employees.FirstOrDefault().last_name; 

        Debug.WriteLine($"Hello { fullName }!");
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
    }
}

员工模型(名称与数据库名称1:1匹配):

[Table("dbo.sandbox_employee")]
public class EmployeeModel
{
    [Key]
    public int employee_id { get; set; }
    public string first_name { get; set; }
    public string last_name { get; set; }
    public int age { get; set; }
    public int company_id { get; set; }
}

dbContext实施:

public class UniContext : DbContext
{
    public UniContext() : base("Name=MyConnString") { }
    public DbSet<EmployeeModel> Employees { get; set; }
}

最后是App.config文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxx" requirePermission="false" />
  </configSections>

  <connectionStrings>
    <add name="MyConnString" connectionString="Integrated Security = SSPI; Persist Security Info = False; Data Source = MyServer; Database = MyDatabase" providerName="System.Data.SqlClient"/>
  </connectionStrings>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7" />
  </startup>

  <entityFramework>

    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">

      <parameters>
        <parameter value="System.Data.SqlClient" />
      </parameters>

    </defaultConnectionFactory>

    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>

</entityFramework>

</configuration>

错误

据我所知,有3种不同的错误。所有这些都被多次抛出......

  1. Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
  2. Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.dll
  3. Exception thrown: 'System.Data.Entity.Core.EntityCommandExecutionException' in EntityFramework.SqlServer.dll

1 个答案:

答案 0 :(得分:0)

现有数据库(通常)不存在两个表dbo.__MigrationHistorydbo.EdmMetadata。实体框架(EF)在初始化期间查找这些表,这会导致我看到的异常。在实例化null之后立即将初始化设置为DbContext将告诉EF不要查找这些表,并且不会发生异常。

using (UniContext db = new UniContext())
{
    Database.SetInitializer<UniContext>(null); // Prevents initialization exceptions

    var emp = db.Employees.First();

    Debug.WriteLine($"Hello { emp.FirstName } { emp.LastName }!");
}
  • 有关详细信息,请参阅this post
  • 感谢@JohnyL帮助我解开谜团。