实体框架 - 空引用异常

Entity Framework - Null Reference Exception

提问人:Dzmitry Shauchuk 提问时间:4/4/2018 最后编辑:Dzmitry Shauchuk 更新时间:4/4/2018 访问量:1017

问:

当我尝试使用EF db上下文从数据库中获取实体时,我有NullReferenceException:

这是我的测试代码:

// it works fine
using (var sql = new SqlConnection("--here is my connection string--"))
{
    sql.Open();
    var cmd = sql.CreateCommand();
    cmd.CommandText = "select field1, field2 from my_table";
    var reader = cmd.ExecuteReader();

    reader.Read();

    // here is true value
    var val = reader.GetValue(0);
}

// failed
var ctx = new BackupDbContext();
var query = ctx.Database.SqlQuery<MyEntity>("select field1, field2 from my_table");
var res = query.ToList(); // NullReferenceException

// failed
var tt = ctx.MyEntities.ToList(); // NullReferenceException

我的 DbContext 和映射:

public class MyEntityMapping : EntityTypeConfiguration<MyEntity>
{
    public MyEntityMapping()
    {
        ToTable("my_table");

        HasKey(p => p.Field1);

        Property(p => p.Field1).HasColumnName("field1");
        Property(p => p.Field2).HasColumnName("field2");
    }
}    

public class BackupDbContext: DbContext
{
    static BackupDbContext()
    {
        Database.SetInitializer<BackupDbContext>(null);
    }

    public BackupDbContext():base("name=BackupDbContext")
    {
        Database.Log = sql => Debug.Write(sql);
    }
    public virtual DbSet<MyEntity> MyEntities { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("dbo");

        modelBuilder.Configurations
                .Add(new MyEntityMapping());
    }
}

我不知道异常的原因是什么。

我有以下堆栈跟踪:

enter image description here

有没有人知道为什么会这样,或者可以给我一个提示?

编辑:

连接: ...

<connectionStrings>
<add name="BackupDbContext" connectionString="Data Source=My_datasource;Encrypt=False;Initial Catalog=my_db;Integrated Security=True;" providerName="System.Data.SqlClient" />      
</connectionStrings>

...enter image description here

C# .NET SQL-Server 实体框架 NullReferenceException

评论

2赞 Manfred Radlwimmer 4/4/2018
什么是 NullReferenceException 的可能重复,我该如何修复它?
0赞 Gaurang Dave 4/4/2018
我认为您的 BackupDbContext 类中缺少连接字符串。尝试公共 BackupDbContext () : base(“BackupDbConStr”) { } 在配置文件的 connectionstring 部分下提及 “BackupDbConStr”。
2赞 CodeCaster 4/4/2018
不是建议的重复,此异常不会从用户代码中引发。EF 似乎在添加错误时从模型构建器中抛出。
0赞 Dzmitry Shauchuk 4/4/2018
CodeCaster,异常的原因可能是什么?
1赞 DevilSuichiro 4/5/2018
什么是代码秒?我用谷歌搜索了一下,我唯一能找到的就是模型优先方法的支持工具——但是,对于模型优先,改变模型构建器的可能性很小。

答:

0赞 Kamol Chandra Roy 4/4/2018 #1

您应该在 webconfig 文件中定义一个 ConnectionString。

 <connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=Your server nane;Initial Catalog=Your database name;Integrated Security=True"
  providerName="System.Data.SqlClient" />
</connectionStrings>

然后你必须在 DbContext 中使用它

  public BackupDbContext():base("DefaultConnection")
  {
    Database.Log = sql => Debug.Write(sql);
  }

现在这个声明应该起作用了。

  var ctx = new BackupDbContext();
  var tt = ctx.MyEntities.ToList();

评论

0赞 Dzmitry Shauchuk 4/4/2018
我做同样的事情,我的数据库上下文有配置文件中的连接字符串
0赞 Kamol Chandra Roy 4/4/2018
再次检查所有东西。我认为你犯了一个愚蠢的错误。而不是这行代码 public BackupDbContext():base(“name=BackupDbContext”) 只写 public BackupDbContext():base(“BackupDbContext”)
0赞 Dzmitry Shauchuk 4/4/2018
请参阅编辑后的帖子 - 上下文有联系