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

Projection throws NullReferenceException #16896

Closed
colinblaise opened this issue Aug 1, 2019 · 1 comment
Closed

Projection throws NullReferenceException #16896

colinblaise opened this issue Aug 1, 2019 · 1 comment

Comments

@colinblaise
Copy link

Similar from what I see at this issue #16724

Exception message: System.NullReferenceException: Object reference not set to an instance of an object.
Stack trace:    at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.EntityProjectionExpression.GetProperty(IProperty property)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.SqlExpressions.SelectExpression.BindProperty(ProjectionBindingExpression projectionBindingExpression, IProperty property)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalSqlTranslatingExpressionVisitor.BindProperty(EntityShaperExpression entityShaperExpression, IProperty property)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalSqlTranslatingExpressionVisitor.BindProperty(Expression source, String propertyName)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalSqlTranslatingExpressionVisitor.VisitMember(MemberExpression memberExpression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalSqlTranslatingExpressionVisitor.VisitExtension(Expression extensionExpression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalSqlTranslatingExpressionVisitor.Translate(Expression expression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalProjectionBindingExpressionVisitor.VisitMemberInit(MemberInitExpression memberInitExpression)
   at System.Linq.Expressions.MemberInitExpression.Accept(ExpressionVisitor visitor)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalProjectionBindingExpressionVisitor.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalProjectionBindingExpressionVisitor.Translate(SelectExpression selectExpression, Expression expression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateSelect(ShapedQueryExpression source, LambdaExpression selector)
   at Microsoft.EntityFrameworkCore.Query.Pipeline.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Relational.Query.Pipeline.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.Pipeline.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.System.Collections.IEnumerable.GetEnumerator()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object value)
   at Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonOutputFormatter.<WriteResponseBodyAsync>d__10.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonOutputFormatter.<WriteResponseBodyAsync>d__10.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Formatters.NewtonsoftJsonOutputFormatter.<WriteResponseBodyAsync>d__10.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeResultAsync>g__Logged|21_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeNextResultFilterAsync>g__Awaited|29_0>d`2.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeNextResourceFilter>g__Awaited|24_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeAsync>g__Logged|17_1>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Immybot.Server.Web.Lib.Middleware.HttpProblemExceptionMiddleware.<InvokeAsync>d__2.MoveNext() in C:\Users\cblaise\code\vs\19\immybot-backend\Immybot.Server.Web\Lib\Middleware\HttpProblemExceptionMiddleware.cs:line 30

Steps to reproduce

var q = _context.Computers.Select(ComputerDto.Projection);
public static Expression<Func<Computer, ComputerDto>> Projection
    {
      get
      {
        return x => new ComputerDto()
        {
          Id = x.Id,
          ComputerName = x.ComputerName,
          IsOnline = x.IsOnline,
          IsPortable = x.IsPortable,
          IsServer = x.IsServer,
          RmmComputerId = x.RmmComputerId,
          RmmLinkId = x.RmmLinkId,
          RmmClientId = x.RmmClientId,
          PrimaryUserDisplayName = x.PrimaryPerson.DisplayName,
          PrimaryUserEmail = x.PrimaryPerson.EmailAddress,
          TenantName = x.Tenant.Name
      };
      }
    }
  }

Further technical details

EF Core version: 3.0.0-preview7.19362.6
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2019

@ajcvickers
Copy link
Contributor

Verified that this works in the nightly builds. Test code:

public class BloggingContext : DbContext
{
    private readonly ILoggerFactory logger = LoggerFactory.Create(c => c.AddConsole());

    public DbSet<Computer> Computers{ get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseLoggerFactory(logger)
            .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Test;ConnectRetryCount=0");
}

public class Program
{
    public static async Task Main()
    {
        using (var context = new BloggingContext())
        {
            context.Database.EnsureDeleted();
            context.Database.EnsureCreated();

            context.Add(new Computer
            {
                ComputerName = "Rainbow",
                PrimaryPerson = new Person
                {
                    DisplayName = "Bungle"
                },
                Tenant = new Tenant
                {
                    Name = "Zippy"
                }
            });

            context.SaveChanges();
        }

        using (var context = new BloggingContext())
        {
            var results = context.Computers.Select(ComputerDto.Projection).ToList();
        }
    }
}

public class Computer
{
    public int Id { get; set; }
    public string ComputerName { get; set; }
    public bool IsOnline { get; set; }
    public bool IsPortable { get; set; }
    public bool IsServer { get; set; }
    public int RmmComputerId { get; set; }
    public int RmmLinkId { get; set; }
    public int RmmClientId { get; set; }
    public string PrimaryUserDisplayName { get; set; }
    public string PrimaryUserEmail { get; set; }
    public string TenantName { get; set; }
    public Person PrimaryPerson { get; set; }
    public Tenant Tenant { get; set; }
}

public class Person
{
    public int Id { get; set; }
    public string DisplayName { get; set; }
    public string EmailAddress { get; set; }
}

public class Tenant
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ComputerDto
{
    public int Id { get; set; }
    public string ComputerName { get; set; }
    public bool IsOnline { get; set; }
    public bool IsPortable { get; set; }
    public bool IsServer { get; set; }
    public int RmmComputerId { get; set; }
    public int RmmLinkId { get; set; }
    public int RmmClientId { get; set; }
    public string PrimaryUserDisplayName { get; set; }
    public string PrimaryUserEmail { get; set; }
    public string TenantName { get; set; }

    public static Expression<Func<Computer, ComputerDto>> Projection
    {
        get
        {
            return x => new ComputerDto()
            {
                Id = x.Id,
                ComputerName = x.ComputerName,
                IsOnline = x.IsOnline,
                IsPortable = x.IsPortable,
                IsServer = x.IsServer,
                RmmComputerId = x.RmmComputerId,
                RmmLinkId = x.RmmLinkId,
                RmmClientId = x.RmmClientId,
                PrimaryUserDisplayName = x.PrimaryPerson.DisplayName,
                PrimaryUserEmail = x.PrimaryPerson.EmailAddress,
                TenantName = x.Tenant.Name
            };
        }
    }
}

@ajcvickers ajcvickers reopened this Oct 16, 2022
@ajcvickers ajcvickers closed this as not planned Won't fix, can't repro, duplicate, stale Oct 16, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants