0

When I tried to get entities from database with the EF db context I have 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:

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:

enter image description here

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>

... enter image description here

Dzmitry Shauchuk
  • 336
  • 2
  • 17
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Manfred Radlwimmer Apr 04 '18 at 07:51
  • I think you are missing connection string in your BackupDbContext class. Try public BackupDbContext () : base("BackupDbConStr") { } Mention "BackupDbConStr" in config file under connectionstring section. – Gaurang Dave Apr 04 '18 at 07:54
  • 2
    Not a duplicate of the proposed one, this exception is not thrown from user code. EF seems to throw from the ModelBuilder while adding an error. – CodeCaster Apr 04 '18 at 07:56
  • CodeCaster, What may be a reason of the exception? – Dzmitry Shauchuk Apr 04 '18 at 08:03
  • My vote is on connection string, where have you defined it? what does ctx.Database.Connection.ConnectionString have in it? – TheGeneral Apr 04 '18 at 08:24
  • My connection string is defined in config file - I used the same in the explicit SqlConnection creation in the first part of the code. It was hidden in my code for security reason. – Dzmitry Shauchuk Apr 04 '18 at 08:38
  • ctx.Database.Connection.ConnectionString has value from the config file – Dzmitry Shauchuk Apr 04 '18 at 08:39
  • @CodeCaster Yeah, the Pavlov duplicate again. Dimitry Could you show this (anonymized) connection string? – Gert Arnold Apr 04 '18 at 08:45
  • Yes, sure - please see the edited post – Dzmitry Shauchuk Apr 04 '18 at 08:56
  • Why is everyone going on about the connection string? The exception is obviously thrown from the metadata builder, which is way, way beyond connecting to the database. – CodeCaster Apr 04 '18 at 08:58
  • CodeCaster, do you have any ideas how it might be fixed? – Dzmitry Shauchuk Apr 04 '18 at 10:33
  • Well it looks like you've triggered a bug in EF's ModelBuilder. You probably have an out-of-sync EDMX. Perhaps try updating it from the database. – CodeCaster Apr 04 '18 at 11:22
  • @CodeCaster This is code-first, no EDMX. The exception is about the database provider, hence the interest in the connection string, the `providerName` part. Dimitry, please specify versions (.Net, EF). – Gert Arnold Apr 04 '18 at 13:19
  • @Gert the `LoadProviderManifest(XmlReader ...` would make it seem that EF is trying to parse an EDMX, right? Perhaps this is a botched attempt to let a model first application become code first, especially since it's EF's code throwing the NRE, so a totally unexpected and unsupported scenario. The OP should explain their entire process of obtaining this particular DbContext. – CodeCaster Apr 04 '18 at 13:30
  • @CodeCaster There's certainly something fishy going on there. Seeing the source code it seems to me that the provider manifest should be known at that point. But if this was the database-first route there should already have been an exception that OnModelCreating was called. Well, haven't got much time to dig into it now. – Gert Arnold Apr 04 '18 at 13:34
  • .NET Framework 4.6.2, EF 6.2. Code second approach – Dzmitry Shauchuk Apr 04 '18 at 13:48
  • 1
    what is code second? I've googled about it and the only thing I can find is a support tool for Model first approach - however, with model first, altered model builders are highly unlikely. – DevilSuichiro Apr 05 '18 at 08:59
  • @CodeCaster No, the manifest is loaded from XML resource string in the provider dll (EntityFramework.SqlServer.dll in this case). And the only caught exception I see in the source code of `Schema.Parse` is `IOException`. Weird. – Ivan Stoev Apr 05 '18 at 12:59
  • "Code second" it is code first to exists database – Dzmitry Shauchuk Apr 05 '18 at 13:02

1 Answers1

0

You should define a ConnectionString in webconfig file .

 <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

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

Now This statement should work.

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