Entity-Framework 6 От одной до многих систем взаимоотношений.Data.Entity.DynamicProxies

В первом приложении EF 6 Code у меня возникают проблемы с отношением «Один-ко-многим» и свойствами навигации в сценарии без отслеживания.

public class User
{
    public int UserId { get; set; }

    public string Name { get; set; }

    public virtual List<File> Files { get; set; }
}

public class File
{
    public int FileId { get; set; }

    public string Number { get; set; }

    public int UserWhoCreatedId { get; set; }

    public User UserWhoCreated { get; set; }
}

Я установил свой объект конфигурации типа следующим образом:

public class FileMap : EntityTypeConfiguration<File>
{
    public FileMap()
    {
        ToTable("File");

        HasKey(e => e.FileId);

        Property(e => e.Number).IsRequired().HasMaxLength(250);

        Property(e => e.UserWhoCreatedId).IsRequired();

        HasRequired(e => e.UserWhoCreated).WithMany(d => d.Files).HasForeignKey(x => x.UserWhoCreatedId);
    }
}

Но когда я приношу свой выбор для просмотра, я получаю следующую ошибку:

var query = Db.File.Include (x => x.UserWhoCreated) .AsNoTracking (). OrderByDescending (x => x.FileId) .ToList ();

{
    "Message": "Ocorreu um erro.",
    "ExceptionMessage": "O tipo 'ObjectContent`1' nao pode serializar o corpo da resposta para o tipo de conteudo 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "Message": "Ocorreu um erro.",
        "ExceptionMessage": "Error getting value from 'Files' on 'System.Data.Entity.DynamicProxies.User_A02A99140F2593106849B9A48413541E1321CFF517D4E87EDBC0AADB1B1B5DC6'.",
        "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
        "StackTrace": "   em Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   em Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
   em System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- Fim do rastreamento de pilha do local anterior onde a excecao foi gerada ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__22.MoveNext()",
        "InnerException": {
            "Message": "Ocorreu um erro.",
            "ExceptionMessage": "When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.",
            "ExceptionType": "System.InvalidOperationException",
            "StackTrace": "   em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.ValidateLoad[TEntity](MergeOption mergeOption, String relatedEndName, Boolean& hasResults)
   em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
   em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
   em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
   em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
   em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)
   em System.Data.Entity.DynamicProxies.User_A02A99140F2593106849B9A48413541E1321CFF517D4E87EDBC0AADB1B1B5DC6.get_Files()
   em GetFiles(Object )
   em Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}

c#,entity-framework-6,lazy-loading,ef-fluent-api,

0

Ответов: 0

Entity-Framework 6 От одной до многих систем взаимоотношений.Data.Entity.DynamicProxies

В первом приложении EF 6 Code у меня возникают проблемы с отношением «Один-ко-многим» и свойствами навигации в сценарии без отслеживания.

public class User
{
    public int UserId { get; set; }

    public string Name { get; set; }

    public virtual List<File> Files { get; set; }
}

public class File
{
    public int FileId { get; set; }

    public string Number { get; set; }

    public int UserWhoCreatedId { get; set; }

    public User UserWhoCreated { get; set; }
}

Я установил свой объект конфигурации типа следующим образом:

public class FileMap : EntityTypeConfiguration<File>
{
    public FileMap()
    {
        ToTable("File");

        HasKey(e => e.FileId);

        Property(e => e.Number).IsRequired().HasMaxLength(250);

        Property(e => e.UserWhoCreatedId).IsRequired();

        HasRequired(e => e.UserWhoCreated).WithMany(d => d.Files).HasForeignKey(x => x.UserWhoCreatedId);
    }
}

Но когда я приношу свой выбор для просмотра, я получаю следующую ошибку:

var query = Db.File.Include (x => x.UserWhoCreated) .AsNoTracking (). OrderByDescending (x => x.FileId) .ToList ();

{
    "Message": "Ocorreu um erro.",
    "ExceptionMessage": "O tipo 'ObjectContent`1' nao pode serializar o corpo da resposta para o tipo de conteudo 'application/json; charset=utf-8'.",
    "ExceptionType": "System.InvalidOperationException",
    "StackTrace": null,
    "InnerException": {
        "Message": "Ocorreu um erro.",
        "ExceptionMessage": "Error getting value from 'Files' on 'System.Data.Entity.DynamicProxies.User_A02A99140F2593106849B9A48413541E1321CFF517D4E87EDBC0AADB1B1B5DC6'.",
        "ExceptionType": "Newtonsoft.Json.JsonSerializationException",
        "StackTrace": "   em Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
   em Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
   em Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
   em System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
   em System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
--- Fim do rastreamento de pilha do local anterior onde a excecao foi gerada ---
   em System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   em System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   em System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__22.MoveNext()",
        "InnerException": {
            "Message": "Ocorreu um erro.",
            "ExceptionMessage": "When an object is returned with a NoTracking merge option, Load can only be called when the EntityCollection or EntityReference does not contain objects.",
            "ExceptionType": "System.InvalidOperationException",
            "StackTrace": "   em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.ValidateLoad[TEntity](MergeOption mergeOption, String relatedEndName, Boolean& hasResults)
   em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(List`1 collection, MergeOption mergeOption)
   em System.Data.Entity.Core.Objects.DataClasses.EntityCollection`1.Load(MergeOption mergeOption)
   em System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()
   em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject)
   em System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__1(TProxy proxy, TItem item)
   em System.Data.Entity.DynamicProxies.User_A02A99140F2593106849B9A48413541E1321CFF517D4E87EDBC0AADB1B1B5DC6.get_Files()
   em GetFiles(Object )
   em Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object target)"
        }
    }
}
00C #, сущность-рамка-6, отложенная загрузка, эф-свободно-апите,
Похожие вопросы