为什么我的超级简单的ASP.NET Web API(mvc4)+实体框架5不起作用? [英] Why my super simple ASP.NET Web API (mvc4)+Entity Framework 5 doesn't work?

查看:106
本文介绍了为什么我的超级简单的ASP.NET Web API(mvc4)+实体框架5不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了几天时间就知道我的工作的问题,但没有运气。

I spent days to know the problems of my work, but no luck.


  1. 我创造了新的MVC4的Web API项目。

  2. 添加EF5与我的数据库(项目>添加> ADO.NET实体数据模型>从数据库这是SQL Azure的创建)。

  3. 添加两个表如下EDMX。两个* .TT文件生成实体和模型类成功。

我可以看到断点(结果)通常给出查询结​​果。
但是JSON给人异常流,而不错误消息。 (即的http://本地主机:41813 / API /表/ 157 返回157,这不能下载一般,157.json被下载。)

I can see the breakpoint(result) gives query result normally. But json gives abnormal stream without error message. (ie, http://localhost:41813/api/sheet/157 returns "157" which cannot download. in general, "157.json" is downloaded)

我的结果我手工制作的POCO风格类复制的属性和它的作品。

I copied properties in results to my handmade POCO-style class and it works.

什么是我的问题吗?我不能使用生成的模型类通过JSON来发送数据。
我很难找出问题,因为任何错误信息,结果断点后没有可用的调试步骤。

What is my problem? I cannot use generated model classes to send data through Json. I hardly find out problem because no error message and no debug step available after the result breakpoint.

推荐答案

究其原因,序列化失败是你的导航属性的 - 而串行器试图走它们会导致循环依赖的对象图。

The reason the serialization fails are yours Navigation Properties - while the serializer is trying to walk the object graph they result in circular dependencies.

有关您简单的示例工作,你周围有几个方法。

For your simple sample to work you have few ways around it.


  1. 删除导航属性 SheetDetail

  2. 裹在你的对象的视图模型的教学班的导航属性省略

  3. 创建一个元数据类 JsonIgnoreAttribute ,然后将其连接到与部分类和 MetadataTypeAttribute
  1. Remove Navigation Property Sheet from SheetDetail
  2. Wrap your objects in ViewModel classes with Navigation Property Sheet omitted
  3. Create a metadata class with JsonIgnoreAttribute and then attach it to your entity with partial class and MetadataTypeAttribute

在这里您可以找到样品的第三溶液(样品做一些假设,因为我不知道你的确切数据类型):

Here you can find sample for third solution (sample makes some assumptions as I don't know your exact data types):

public class SheetDetailSerializationMetadata
{
    [JsonIgnore]
    public Sheet Sheet { get; set; }
}

[MetadataType(typeof(SheetDetailSerializationMetadata))]
public partial class SheetDetail
{ 
}

这篇关于为什么我的超级简单的ASP.NET Web API(mvc4)+实体框架5不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆