Search code examples
c#asp.netentity-frameworkmodelsnullreferenceexception

"Object reference not set to an instance of an object" on navigation property


I have this code:

IQueryable<Dealer> dealers = db.Dealers.Include(x => x.Statuses);
this.view.Table = dealers
    .Select(x => new DealerRow
    {
        Id = x.Id,
        LastStatus = x.Statuses.FirstOrDefault()
    })
    .ToList();

and the line that starts with this.view.Table = dealers is where this exception occurs:

Object reference not set to an instance of an object.

The stack trace is the following:

[NullReferenceException: Object reference not set to an instance of an object.]
   MySql.Data.Entity.SelectStatement.AddDefaultColumns(Scope scope) +293
   MySql.Data.Entity.SelectStatement.Wrap(Scope scope) +36
   MySql.Data.Entity.SelectGenerator.Visit(DbApplyExpression expression) +236
   System.Data.Entity.Core.Common.CommandTrees.DbApplyExpression.Accept(DbExpressionVisitor`1 visitor) +64
   MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type) +32
   MySql.Data.Entity.SelectGenerator.HandleJoinExpression(DbExpressionBinding left, DbExpressionBinding right, DbExpressionKind joinType, DbExpression joinCondition) +77
   MySql.Data.Entity.SelectGenerator.Visit(DbJoinExpression expression) +48
   System.Data.Entity.Core.Common.CommandTrees.DbJoinExpression.Accept(DbExpressionVisitor`1 visitor) +64
   MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type) +32
   MySql.Data.Entity.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type) +22
   MySql.Data.Entity.SelectGenerator.Visit(DbSortExpression expression) +76
   System.Data.Entity.Core.Common.CommandTrees.DbSortExpression.Accept(DbExpressionVisitor`1 visitor) +64
   MySql.Data.Entity.SqlGenerator.VisitInputExpression(DbExpression e, String name, TypeUsage type) +32
   MySql.Data.Entity.SelectGenerator.VisitInputExpressionEnsureSelect(DbExpression e, String name, TypeUsage type) +22
   MySql.Data.Entity.SelectGenerator.Visit(DbProjectExpression expression) +53
   System.Data.Entity.Core.Common.CommandTrees.DbProjectExpression.Accept(DbExpressionVisitor`1 visitor) +64
   MySql.Data.Entity.SelectGenerator.GenerateSQL(DbCommandTree tree) +68
   MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree) +328
   System.Data.Entity.Core.Common.DbProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext) +13
   System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext) +127
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition..ctor(DbProviderFactory storeProviderFactory, DbCommandTree commandTree, DbInterceptionContext interceptionContext, IDbDependencyResolver resolver, BridgeDataReaderFactory bridgeDataReaderFactory, ColumnMapFactory columnMapFactory) +1420
   System.Data.Entity.Core.EntityClient.Internal.EntityProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree, DbInterceptionContext interceptionContext) +103
   System.Data.Entity.Core.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree, DbInterceptionContext interceptionContext) +127
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.CreateCommandDefinition(ObjectContext context, DbQueryCommandTree tree) +151
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlanFactory.Prepare(ObjectContext context, DbQueryCommandTree tree, Type elementType, MergeOption mergeOption, Boolean streaming, Span span, IEnumerable`1 compiledQueryParameters, AliasGenerator aliasGenerator) +161
   System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) +1027
   System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__6() +39
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
   System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +155
   System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute(Func`1 operation) +9
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +281
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +11
   System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +45
   System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +387
   System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
   DealersPresenter.RefreshTable() in File1.cs:98
   DealersListPage.Filter(Object sender, EventArgs e) in File2.aspx.cs:37
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9659822
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

Specifically, if I comment out LastStatus from the select the program compiles and runs perfectly. So I'm assuming Statuses is the issue here.

The one to many relationship is setup like this:

[Table("dealers")]
public class Dealer
{

    public Dealer()
    {
        Statuses = new List<DealerStatus>();
    }

    [Key]
    [Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public virtual ICollection<DealerStatus> Statuses { get; set; }

}

and:

[Table("dealer_statuses")]
public class DealerStatus
{

    [Key]
    [Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required]
    [ForeignKey("Dealer")]
    [Column("id_dealer")]
    public int DealerId { get; set; }
    public virtual Dealer Dealer { get; set; }

    [Required]
    [Column("note")]
    public string Note { get; set; }

}

I've read other 5 questions about it. I tried calling Include and similars. I've also checked that the default constructor for Dealer initializes an empty list.

What's causing this exception?


Solution

  • After trying to remove virtual from the collection, and other kind of eager loading, I've moved the Select after the ToList call (which will eagerly load everything) but at least it compiles and runs.

    Updating to the latest 6.9.9 MySql.Data.Entity also didn't work for me.