实体框架 - 空引用异常

时间:2018-04-04 07:38:21

标签: c# .net sql-server entity-framework nullreferenceexception

当我尝试使用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

1 个答案:

答案 0 :(得分:0)

您应该在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();