简体   繁体   English

实体框架-空引用异常

[英]Entity Framework - Null Reference Exception

When I tried to get entities from database with the EF db context I have NullReferenceException: 当我尝试从具有EF db上下文的数据库中获取实体时,我遇到了NullReferenceException:

Here is my testing code: 这是我的测试代码:

// 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

My DbContext and mapping: 我的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());
    }
}

I have no idea what is the reason of the exception. 我不知道例外的原因是什么。

I have the following stack trace: 我有以下堆栈跟踪:

在此处输入图片说明

Does anyone have idea why it is so or can give me a hint? 有谁知道为什么会这样,还是可以给我一个提示?

Edit: 编辑:

Connection: ... 连接:...

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

... ... 在此处输入图片说明

You should define a ConnectionString in webconfig file . 您应该在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>

Then You have to use it in DbContext 然后,您必须在DbContext中使用它

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

Now This statement should work. 现在,此语句应该起作用。

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

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

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