gpt4 book ai didi

entity-framework - Asp.Net Web API错误: The 'ObjectContent` 1' type failed to serialize the response body for content type ' application/xml; charset=utf-8'

转载 作者:行者123 更新时间:2023-12-03 07:47:37 26 4
gpt4 key购买 nike

最简单的示例,我获取一个集合并尝试通过 Web API 输出它:

// GET api/items
public IEnumerable<Item> Get()
{
return MyContext.Items.ToList();
}

我收到错误:

Object of type
'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]' cannot be converted to type
'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'

这是新代理的一个非常常见的错误,我知道我可以通过设置来修复它:

MyContext.Configuration.ProxyCreationEnabled = false;

但这违背了我想做的很多事情的目的。有更好的办法吗?

最佳答案

我建议仅在您不需要或给您带来麻烦的地方禁用代理创建。您不必全局禁用它,您只需通过代码禁用当前的数据库上下文...

    [HttpGet]
[WithDbContextApi]
public HttpResponseMessage Get(int take = 10, int skip = 0)
{
CurrentDbContext.Configuration.ProxyCreationEnabled = false;

var lista = CurrentDbContext.PaymentTypes
.OrderByDescending(x => x.Id)
.Skip(skip)
.Take(take)
.ToList();

var count = CurrentDbContext.PaymentTypes.Count();

return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count });
}

这里我只禁用了这个方法中的ProxyCreation,因为对于每个请求都会创建一个新的DBContext,因此我只禁用了这种情况下的ProxyCreation。希望对您有帮助

关于entity-framework - Asp.Net Web API错误: The 'ObjectContent` 1' type failed to serialize the response body for content type ' application/xml; charset=utf-8',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13959048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com