Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insert entity in non existing table throws NullException #9599

Closed
JeanCollas opened this issue Aug 28, 2017 · 12 comments
Closed

Insert entity in non existing table throws NullException #9599

JeanCollas opened this issue Aug 28, 2017 · 12 comments
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug
Milestone

Comments

@JeanCollas
Copy link

JeanCollas commented Aug 28, 2017

The following code generates a -not dev-friendly- error

        builder.Entity<MyEntity>(b =>
        {
            b.HasKey(e => e.Guid);
            b.ToTable("NotExistingTable");
        });

    public DbSet<MyEntity> MyTable { get; set; }
DbContext.MyTable.Add(new MyEntity(){SomeField="test"});
await DbContext.SaveChangesAsync();

The error:

Message:

Object reference not set to an instance of an object.

   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair`2 keyValuePair)
   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
   at Microsoft.EntityFrameworkCore.Internal.CoreLoggerExtensions.SaveChangesFailed(IDiagnosticsLogger`1 diagnostics, DbContext context, Exception exception)
   at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__48.MoveNext()

It would be nice to have something saying that the table could not be found or something like this :)

@anpete
Copy link
Contributor

anpete commented Sep 5, 2017

@JeanCollas I'm unable to repro this so far. Can you confirm that you are using the 2.0 version of all packages, including Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.

@xrkolovos
Copy link

I get this error with Pomelo.EntityFrameworkCore.MySql provider
When i call savechanges. Very confusing error, can't understand what it is. The table exists.

Object reference not set to an instance of an object.

at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair`2 keyValuePair)
 at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
 at Microsoft.EntityFrameworkCore.Internal.CoreLoggerExtensions.SaveChangesFailed(IDiagnosticsLogger`1 diagnostics, DbContext context, Exception exception)
 at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__48.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
 at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
 at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()

@thoemy
Copy link

thoemy commented Oct 21, 2017

I see that issue during integration testing my ASP Net app. Multiple TestServers are created and disposed and later tests are executed that don't rely on these TestServers. But seem to be affected somehow by them.

For example this test is fine when it is executed without prior creation of the TestServers.

        [Fact]
        public void CreateEmptyCalendar() {
            using (var context = TestUtils.GetContext()) {
                context.Calendars.Add(new Calendar());
                Assert.Throws<DbUpdateException>(() => context.SaveChanges());
            }
        }

But if fails with a System.NullReferenceException in DatabaseErrorPageMiddleware.OnNext(KeyValuePair<string, object> keyValuePair) when the integration tests where run previously. GetContext() simply creates a new DbContext using an SqliteConnection.

The exception goes away if I don't call app.UseDatabaseErrorPage(); in my Startup class.

I'll see if I can come up with a small test case.

@lcalabrese
Copy link

I'm seeing this as well. It seems like if anything throws an exception inside SaveChanges(Async) this happens. I've disabled Just My Code in the debugger and am able to see the real exception before it gets caught by the framework - in this case a SqliteException (Error 19 not null constraint failed FWIW). Similar to others here this is happening from an xUnit integration test.

What seems to happen is the SqliteException is getting caught inside the framework and then turned into a DbUpdateException which is then being caught again inside the framework. Somewhere after this we get a NullReferenceException at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair2 keyValuePair)`, same as above.

I'm out of time right now so I can't investigate further but hopefully this is a step in the right direction.

@lcalabrese
Copy link

Ok so apparently what is happening is _localDiagnostic.Value is getting set to null somewhere between the time it's being set in DatabaseErrorPageMiddleware.Invoke(HttpContext) at DatabaseErrorPageMiddleware.cs:103 and when it is used in DatabaseErrorPageMiddleware.OnNext(KeyValuePair<string, object>) at DatabaseErrorPageMiddleware.cs:223 . I'm not really sure why and I can't seem to track down where it is being set to null. Perhaps there is a problem with AsyncLocal?

Hopefully this helps track it down and get the problem fixed.

@ajcvickers
Copy link
Contributor

@anpete Can you bump up the priority of investigating this, also considering dotnet/aspnetcore#2820

@anpete
Copy link
Contributor

anpete commented Jan 24, 2018

@ajcvickers Will do.

anpete added a commit to aspnet/Diagnostics that referenced this issue Jan 26, 2018
…eException when ef exception occur in background task

Fix dotnet/efcore#9599 - Insert entity in non existing table throws NullException

Added null checks to async local access in event callback.

Related to dotnet/aspnetcore#2825
anpete added a commit to aspnet/Diagnostics that referenced this issue Jan 26, 2018
Fix dotnet/aspnetcore#2820 - UseDatabaseErrorPage throws NullReferenceException when ef exception occur in background task
Fix dotnet/efcore#9599 - Insert entity in non existing table throws NullException

Added null checks to async local access in event callback.

Related to dotnet/aspnetcore#2825
anpete added a commit to aspnet/Diagnostics that referenced this issue Jan 26, 2018
Fix dotnet/aspnetcore#2820 - UseDatabaseErrorPage throws NullReferenceException when ef exception occur in background task
Fix dotnet/efcore#9599 - Insert entity in non existing table throws NullException

Added null checks to async local access in event callback.

Related to dotnet/aspnetcore#2825
anpete added a commit to aspnet/Diagnostics that referenced this issue Jan 26, 2018
Fix dotnet/aspnetcore#2820 - UseDatabaseErrorPage throws NullReferenceException when ef exception occur in background task
Fix dotnet/efcore#9599 - Insert entity in non existing table throws NullException

Added null checks to async local access in event callback.

Related to dotnet/aspnetcore#2825
@anpete anpete added closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug labels Jan 26, 2018
@Logopher
Copy link

I just saw this problem in EF Core 2.0.3 (included via Microsoft.AspNetCore.All 2.0.8). In my attempt to build a minimal test case, the problem disappeared and gave way to a much more helpful exception, which explained that a TimeSpan of 4 days is too big for a column in SqlServer.

@mtfash
Copy link

mtfash commented Aug 26, 2018

Using Dot Net Core 2.0 framework and EFCore 2.0.3 I have this error but I am not calling SaveChagnes(). However it happens when calling below query:

return await query.Take(100).ToListAsync();

query is an IQueryable object from my dbset.

I cannot reproduce it but it happens often.

Here is the stack trace:

System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.System.IObserver<System.Collections.Generic.KeyValuePair<System.String,System.Object>>.OnNext(KeyValuePair`2 keyValuePair)
   at System.Diagnostics.DiagnosticListener.Write(String name, Object value)
   at Microsoft.EntityFrameworkCore.Internal.CoreLoggerExtensions.QueryIterationFailed(IDiagnosticsLogger`1 diagnostics, Type contextType, Exception exception)
   at Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.<MoveNext>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Linq.AsyncEnumerable.<Aggregate_>d__6`3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at RubyVAS.Controllers.BackgroundRenewal.<GetSubscriptions>d__5.MoveNext() in C:\Users\xxx\Source\Repos\xxx\xxx\Controllers\RenewalController.cs:line 421
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at RubyVAS.Controllers.BackgroundRenewal.<Roshan>d__4.MoveNext() in C:\Users\xxx\Source\Repos\xxx\xxx\Controllers\RenewalController.cs:line 344

@smitpatel
Copy link
Contributor

@mustafashujaie - This issue has been fixed in 2.1 release. Which version of packages are you using? Fix is in Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore package.

@mtfash
Copy link

mtfash commented Aug 26, 2018

This is the .csproj file:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
    <UserSecretsId>aspnet-RubyVAS-7B5F8BD4-0125-4090-BA45-4785CF064F2A</UserSecretsId>
	<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Core.Flash" Version="1.0.0" />
    <PackageReference Include="DotnetCOre.NPOI" Version="1.0.2" />
    <PackageReference Include="Hangfire" Version="1.6.19" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.6" />
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.6" />
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.3" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.0.4" PrivateAssets="All" />
    <PackageReference Include="RabbitMQ.Client" Version="5.0.1" />
    <PackageReference Include="X.PagedList.Mvc.Core" Version="7.2.4" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.Extensions.SecretManager.Tools" Version="2.0.0" />
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" />
  </ItemGroup>

</Project>

@smitpatel
Copy link
Contributor

@mustafashujaie - You are using 2.0.8 version of AspnetCore.All. Please upgrade all AspNet related packages to 2.1 release in order to get the bug fix. Read this for more info on how to upgrade. https://docs.microsoft.com/en-us/aspnet/core/migration/20_21?view=aspnetcore-2.1

@ajcvickers ajcvickers modified the milestones: 2.1.0-preview2, 2.1.0 Nov 11, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. type-bug
Projects
None yet
Development

No branches or pull requests

9 participants