Base solution for your next web application
Open Closed

EF6 Lazy Loading webservice error #3894


User avatar
0
Garysund created

Hi There

I am using the regular EF version not core. I have got the following entities.

[Table("BusinessUnits")]
    public class BusinessUnit : FullAuditedEntity
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string SharepointMapping { get; set; }
    }

  [Table("Brands")]
    public class Brand : FullAuditedEntity
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string SharepointMapping { get; set; }
        [ForeignKey("BusinesUnitId")]
        public virtual BusinessUnit BusinessUnit { get; set; }
        public virtual int BusinesUnitId { get; set; }

    }

 [Table("Products")]
    public class Product : FullAuditedEntity
    {
        [Required]
        public string Name { get; set; }
        [Required]
        public string SharepointMapping { get; set; }
        [ForeignKey("BrandId")]
        public virtual Brand Brand { get; set; }
        public virtual int BrandId { get; set; }

    }

The navigation properties - lazy loading works for the first two entities but when I try list the Products Entity from a webservice call I get the following error.

{"message":"An error has occurred.","exceptionMessage":"The 'ObjectContent1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","exceptionType":"System.InvalidOperationException","stackTrace":null,"innerException":{"message":"An error has occurred.","exceptionMessage":"Error getting value from 'BusinessUnit' on 'System.Data.Entity.DynamicProxies.Brand_486DF76111C074CB5B97521E6C0339967681A92DC158A5A4CBD2B5E9A75D0277'.","exceptionType":"Newtonsoft.Json.JsonSerializationException","stackTrace":" at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","innerException":{"message":"An error has occurred.","exceptionMessage":"The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.","exceptionType":"System.ObjectDisposedException","stackTrace":" at System.Data.Entity.Core.Objects.ObjectContext.get_Connection()\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption)\r\n at System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.EntityReference1.Load(MergeOption mergeOption)\r\n at System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)\r\n at System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass72.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)\r\n at System.Data.Entity.DynamicProxies.Brand_486DF76111C074CB5B97521E6C0339967681A92DC158A5A4CBD2B5E9A75D0277.get_BusinessUnit()\r\n at GetBusinessUnit(Object )\r\n at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"}}}

Here is the service that is being used for the lookup.

var products = _productRepository.GetAll().ToList();

Is there an issue with getting entities 3 levels deep.

Thanks


3 Answer(s)
  • User Avatar
    0
    alper created
    Support Team

    you have to use eager load

    _productRepository.GetAll().Include(t => t.Brand).Include(x=> x.Brand.Select(y=>y.BusinessUnit))
    
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @Garysund,

    Are you returning entities via webservice ? If so, can you try to return Dtos instead ?

  • User Avatar
    0
    Garysund created

    Solved!

    Just use DTOS as per @ismcagdas

    [AutoMapFrom(typeof(Product))]
        public class ProductListDto : FullAuditedEntityDto
        {
            public string Name { get; set; }
            public string SharepointMapping { get; set; }
            public string BrandName { get; set; }
            public string BusinessUnitName { get; set; }
           
    
        }