Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# asp.net web api中的即时加载_C#_Asp.net_Asp.net Web Api_Entity Framework 6 - Fatal编程技术网

C# asp.net web api中的即时加载

C# asp.net web api中的即时加载,c#,asp.net,asp.net-web-api,entity-framework-6,C#,Asp.net,Asp.net Web Api,Entity Framework 6,大家好,我最近开始学习如何编写web api 我在winform中有一个项目,我想使用web api重新制作,问题是我不能使用即时加载,我总是得到错误500,代码如下: public HttpResponseMessage GetExpediente() { db.Configuration.ProxyCreationEnabled = false; var expediente = db.Expediente.Include(x=>x.Docume

大家好,我最近开始学习如何编写web api

我在winform中有一个项目,我想使用web api重新制作,问题是我不能使用即时加载,我总是得到错误500,代码如下:

public HttpResponseMessage GetExpediente()
    {
        db.Configuration.ProxyCreationEnabled = false;
        var expediente = db.Expediente.Include(x=>x.Documento);
        if (expediente.Any())
        {
            return Request.CreateResponse(HttpStatusCode.OK, expediente);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                "No se encontraron expedientes.");
        }
    }
public class A
{
    public B B { get; set; }
}

public class B
{
    public virtual ICollection<A> A { get; set; }
}
我经常遇到的错误是:

{"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":{"Message":"An error has occurred.","ExceptionMessage":"Self referencing loop detected for property 'Expediente' with type 'Modelo.Expediente'. Path '[0].Documento[0]'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)\r\n   en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n   en Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n   en System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   en System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n   en System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)\r\n   en System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- Fin del seguimiento de la pila de la ubicación anterior donde se produjo la excepción ---\r\n   en System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   en System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()"}}
{“Message”:“发生了错误”,“ExceptionMessage”:“ObjectContent`1”类型未能序列化内容类型“application/json;charset=utf-8”的响应正文”,“ExceptionType”:“System.invalidoctionexception”,“StackTrace”:null,“InnerException”:{“Message”:“发生了错误”,“ExceptionMessage”:”:“检测到类型为'Modelo.phamplite'。路径'[0].Documento[0]',“ExceptionType:“Newtonsoft.Json.JsonSerializationException”,“StackTrace:“en Newtonsoft.Json.Serialization.jsonSerializationPrinternalWriter.CheckForCircularReference”(JsonWriter编写器,对象值,JsonProperty属性,JsonContract合同,JsonContainerContract容器合同,JsonProperty容器属性)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculateProperty值(JsonWriter编写器,对象值,JsonContainerContract合同,JsonProperty成员,JsonProperty属性,JsonContract&memberContract,对象&memberValue)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,JsonObjectContract合约,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.serializationValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter-writer,IEnumerable-values,JsonArrayContract-contract,JsonProperty成员,JsonContainerContract-collectionContract,JsonProperty-containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter编写器,对象值,JsonObjectContract合约,JsonProperty成员,JsonContainerContract collectionContract,JsonProperty containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.serializationValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter-writer,IEnumerable-values,JsonArrayContract-contract,JsonProperty成员,JsonContainerContract-collectionContract,JsonProperty-containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter编写器,对象值,JsonContract valueContract,JsonProperty成员,JsonContainerContract containerContract,JsonProperty containerProperty)\r\n en Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter JsonWriter,对象值,类型objectType)\r\n en Newtonsoft.Json.JsonSerializer.Serializer\n(JsonWriter JsonWriter,对象值,类型objectType)\r\n en System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型类型,对象值,流writeStream,编码有效编码)\r\n en System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(类型,对象值,流writeStream writeStream,编码有效编码)\r\n en System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(类型、对象值、流writeStream、HttpContent内容)\r\n en System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(类型类型、对象值、流写入流、HttpContent内容、TransportContext TransportContext、CancellationToken CancellationToken)\r\n---在系统运行时、编译器服务、TaskWaiter.ThrowForNonSuccess(任务任务任务)之前,为ubicación的用户提供服务\r\n en System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)\r\n en System.Web.Http.WebHost.HttpControllerHandler.d_u1b.MoveNext()“}
我一直在寻找信息。这可能会帮助我,但我总是发现我应该禁用懒散加载,我做到了,但它没有起作用,这里有人能帮我吗

顺便说一句,我的目标是从windows窗体项目中使用此api,有人告诉我这样做:

var emp1 = response.Content.ReadAsStringAsync().Result;
        var result = JsonConvert.DeserializeObject<IEnumerable<ExpedientePOCO>>(emp1);
var emp1=response.Content.ReadAsStringAsync().Result;
var result=JsonConvert.DeserializeObject(emp1);
但是我从var emp1=…的行中得到的是一个错误500。哦,当我从上下文中获取include时,它工作得很好,但是我想使用渴望加载,希望您能提供帮助

谢谢!谢谢

我对DTO的理解是:

 public HttpResponseMessage GetExpediente()
    {
        db.Configuration.ProxyCreationEnabled = false;
        var expediente = db.Expediente.Include(x=>x.Documento);
        List<ExpedientePOCO> expPOCO = new List<ExpedientePOCO>();
        foreach (var entidad in expediente)
        {
            String fecha = String.Format("{0:dd-MM-yyy}", entidad.FechaCreacion);
            ExpedientePOCO expedientePOCO = new ExpedientePOCO()
            {
                idExpediente = entidad.idExpediente,
                NombreExpediente = entidad.NombreExpediente,
                FechaCreacion = Convert.ToDateTime(fecha),
                DuenioExpediente = entidad.DuenioExpediente,
                CantidadDocumento = entidad.CantidadDocumento
            };
            foreach (var documentos in entidad.Documento)
            {
                DocumentoPOCO documento = new DocumentoPOCO()
                {
                    idDocumento = documentos.idDocumento,
                    idExpediente = documentos.idExpediente,
                    NombreDocumento = documentos.NombreDocumento,
                    FechaCreacion = documentos.FechaCreacion,
                    Expedientes = expedientePOCO
                };
                expedientePOCO.Documentos.Add(documento);
            }
            expPOCO.Add(expedientePOCO);
        }
        if (expPOCO.Any())
        {
            return Request.CreateResponse(HttpStatusCode.OK, expPOCO);
        }
        else
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound,
                "No se encontraron expedientes.");
        }
    }
public HttpResponseMessage getenvigate()
{
db.Configuration.ProxyCreationEnabled=false;
var便利=数据库便利。包括(x=>x.Documento);
List expPOCO=新列表();
foreach(权宜之计中的var entidad)
{
字符串fecha=String.Format(“{0:dd-MM-yyy}”,entidad.fechacreation);
权宜TEPOCO权宜TEPOCO=新权宜TEPOCO()
{
idexpedinte=entidad.idexpedinte,
nombreexpedinte=entidad.nombreexpedinte,
fechacreaction=转换到当前时间(fecha),
dueniophamplite=entidad.dueniophamplite,
CantidadDocumento=entidad.CantidadDocumento
};
foreach(entidad.Documento中的var documentos)
{
DocumentoPOCO documento=新DocumentoP
public class ADTO
{
    // needed properties only
    public BDTO B { get; set; }
}

public class BDTO
{
    // needed properties only
    public List<ADTO> A { get; set; }
}
var data = db.As
    .Select(a => new ADTO 
    {
        x = a.x ....
        B = new BDTO { x = a.B.x ...  }
    }
    .ToList();
var data = context.B
    .Select(b => new BDTO
    {
        x = b.x ...
        A = b.A
            .Select(a => new ADTO
            {
                x = a.x ...
            }
            .ToList()
    }
    .ToList();