Ошибка «Тип ObjectContent`1» не удалось сериализовать .... »при получении загруженного списка объектов - PullRequest
0 голосов
/ 13 ноября 2018

Review.cs

namespace DatabaseProject.Models
{
    public class Review
    {
        public int Id { get; set; }
        public string Text { get; set; }
        public int Stars { get; set; }
        [Required]
        public Product Product { get; set; }
        [Required]
        public Customer Customer { get; set; }
    }
}

Product.cs

namespace DatabaseProject.Models
{
    public class Product
    {
        public Product()
        {
            Reviews = new List < Review >();
        }

        public int Id { get; set; }
        public Catagory Catagory { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string Specification { get; set; }
        public List<Review> Reviews { get; set; }
    }
}

Продукт содержит список отзывов.

Способ получения товара по идентификатору в ProductService.cs

public Product Get(int id)
{
    using (var context = new ShopDbContext())
    {
        context.Database.Log = Console.WriteLine;
        return context.Products.Include(p => p.Reviews).FirstOrDefault(p => p.Id == id);
        // return context.Products.Find(id);
    }
}

Получить метод в контроллере продукта

[HttpGet]
[Route("api/products/{id}")]
public Product Get(int id)
{
    return ProductService.Get(id);
}

Если я сделаю return context.Products.Find(id);, продукт будет передан правильно. список отзывов лениво загружен.

Но если я сделаю return context.Products.Include(p => p.Reviews).FirstOrDefault(p => p.Id == id); Это позволит загрузить список отзывов вместе с объектом продукта. Я получаю ошибку, когда я делаю это ..

{
    "$id": "1",
    "Message": "An error has occurred.",
    "ExceptionMessage": "The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "$id": "2",
        "Message": "An error has occurred.",
        "ExceptionMessage": "Error getting value from 'Customer' on 'System.Data.Entity.DynamicProxies.Review_748A28BF6E2F775DBAC292070955775A1A68595A2F1196D974AE8DBBFC4B9C04'.",
        "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.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.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__22.MoveNext()",
        "InnerException": {
            "$id": "3",
            "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.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)\r\n   at System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption)\r\n   at System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.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__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item)\r\n   at System.Data.Entity.DynamicProxies.Review_748A28BF6E2F775DBAC292070955775A1A68595A2F1196D974AE8DBBFC4B9C04.get_Customer()\r\n   at GetCustomer(Object )\r\n   at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...