nas*_*ski 35 entity-framework entity-framework-4 asp.net-web-api
最简单的例子,我得到一个集合并尝试通过Web API输出:
// GET api/items
public IEnumerable<Item> Get()
{
return MyContext.Items.ToList();
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
'System.Data.Objects.ObjectQuery`1 [Dcip.Ams.BO.EquipmentWarranty]' 类型的对象 无法转换为类型
'System.Data.Entity.DbSet`1 [Dcip.Ams.BO.EquipmentWarranty]'
这是与新代理相关的一个非常常见的错误,我知道我可以通过设置来修复它:
MyContext.Configuration.ProxyCreationEnabled = false;
Run Code Online (Sandbox Code Playgroud)
但这违背了我想要做的很多事情的目的.有没有更好的办法?
Mah*_*hdi 25
如果你有导航属性并且你不想让它们非虚拟,你应该使用JSON.NET并将App_Start中的配置更改为使用JSON而不是XML!
安装JSON.NET后从NuGet中,在Register方法的WebApiConfig.cs中插入此代码
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
Run Code Online (Sandbox Code Playgroud)
vis*_*uqi 24
我建议只在您不需要或导致麻烦的地方禁用代理创建.您不必在全局禁用它,您只需通过代码禁用当前的数据库上下文...
[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 });
}
Run Code Online (Sandbox Code Playgroud)
这里我只在这个方法中禁用了ProxyCreation,因为对于每个请求都创建了一个新的DBContext,因此我只为这种情况禁用了ProxyCreation.希望能帮助到你
Oli*_*ver 12
如果您有导航属性,则将它们设置为非虚拟.映射仍然有效,但它会阻止创建无法序列化的动态代理实体.
没有延迟加载在WebApi中没问题,因为你没有持久连接,而且你还是运行了.ToList().
小智 7
我只是根据需要禁用了代理类:
// GET: ALL Employee
public IEnumerable<DimEmployee> Get()
{
using (AdventureWorks_MBDEV_DW2008Entities entities = new AdventureWorks_MBDEV_DW2008Entities())
{
entities.Configuration.ProxyCreationEnabled = false;
return entities.DimEmployees.ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
在Global.asax.cs 的Application_Start函数中添加以下代码:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
Run Code Online (Sandbox Code Playgroud)
这会指示 API 将每个响应序列化为 JSON 并删除 XML 响应。
| 归档时间: |
|
| 查看次数: |
44001 次 |
| 最近记录: |