Search code examples
c#asp.net-mvcasp.net-mvc-5odata

Error trying $expand on a nullable Navigation Property


I'm using the latest ASP.NET nightly builds. On my REST API (EntitySetController based), when I try to $expand a navigation property which is null in the database, I get the following error:

"message": "The EDM instance of type '[Communicator.Model.ContentTemplateGroup Nullable=True]' is missing the property 'GUID'.",
"type": "System.InvalidOperationException",
"stacktrace": "   at System.Web.Http.OData.EntityInstanceContext.GetPropertyValue(String propertyName)

Rest call Im macking is:

/ContentTemplate?$expand=ContentTemplateGroup

This happens only when there are 'ContentTemplate' instances with no 'ContentTemplateGroup' existing in database (null FK). For ContentTemplates that has ContentTemplateGroup, $expand works fine. My Entities look like follows:

public class ContentTemplate: IIdentifier
{
    public int? Id { get; set; }

    [Required]
    public Guid GUID { get; set; }

    public virtual ContentTemplateGroup ContentTemplateGroup { get; set; }
    public virtual ICollection<ContentTemplateField> ContentTemplateFields { get; set; }
}

public class ContentTemplateGroup : IIdentifier
{
    public int? Id { get; set; }

    [Required]
    public Guid GUID { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual IList<ContentTemplate> ContentTemplate { get; set; }
}

I don't get this error when I try to expand Navigation properties with collections. Following works like a charm:

http://localhost:64316/rest/ContentTemplate?$expand=ContentTemplateFields

Update: Before making the entity primary keys nullable (int?) I was getting a different error for the same problem context. Error was:

"message": "The cast to value type 'System.Int32' failed because the materialized value is null. Either the result type's generic parameter or the query must use a nullable type.",
"type": "System.InvalidOperationException",
"stacktrace": "   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetColumnValueWithErrorHandling[TColumn](Int32 ordinal)\r\n   at lambda_method(Closure , Shaper )\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)\r\n   at System.Data.Entity.Core.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()\r\n   at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()\r\n   at System.Web.Http.OData.Formatter.Serialization.ODataFeedSerializer.WriteFeed(IEnumerable enumerable, ODataWriter writer, ODataSerializerContext writeContext)

Solution

  • This is a known issue (1043: $expand fails when the navigation property being expanded is null). I have checked in a fix for this just now. Can you grab our latest nightly build tomorrow and confirm if the issue is gone?