有父子关系时的WebAPI与EF code首先生成错误 [英] WebApi with EF Code First generates error when having parent child relation

查看:107
本文介绍了有父子关系时的WebAPI与EF code首先生成错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打破我的头在这个问题上。我没有找到关于它在互联网上的东西,但没有一个明确的答案。我的问题:

I am breaking my head over this issue. I did find something on the internet about it, but not a clear answer. My problem:

我要在MVC3 Web应用程序的模型部分类:
父类和ChildClass
在父类有一个List类型的属性Children

I have to classes in Model section of an MVC3 web app: ParentClass and ChildClass On ParentClass there is a property Children of type List

我用EF code首先,在数据库,整齐地生成一个父表和一个子表给我。

I used EF Code First, which neatly generates a parent table and a child table for me in the database.

现在我需要休息的服务,还给一个列表或一个单一的父类。

Now I need a REST service that gives back a List or a single ParentClass.

当我从父类中删除属性Children是没有问题的。但随着propoerty儿童有我不断收到一个错误。

When I remove the property Children from the ParentClass there is no problem. But with the propoerty Children there I keep getting an error.

错误:的类型System.Data.Entity.DynamicProxies.ParentClass_A0EBE0D1022D01EB84B81873D49DEECC60879FC4152BB115215C3EC16FB8003A是没有预料到,使用XmlInclude或SoapInclude属性来指定不是静态已知类型。}

有些code:

类:

     public class ParentClass
{
    public int ID { get; set; }
    public string Name {get;set;}
    public virtual List<ChildrenClass> Children { get; set; }

}

public class ChildrenClass
{
    public int ID { get; set; }
    public string MyProperty { get; set; }
}

服务:

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
[ServiceBehavior(IncludeExceptionDetailInFaults = true)] 
public class MyService
{

    static MyContext db;
    public MyService() { db = new MyContext(); }


    [WebGet(UriTemplate = "")]
    public List<ParentClass> GetParents()
    {
        var result = db.Parents.ToList();
        return result;

    }

我不会callinh此服务时,得到的结果。我在做什么错了?

I will not get the result when callinh this service. What am I doing wrong?

推荐答案

我不得不DisableProxyCreation在上下文配置:

I had to DisableProxyCreation in the context configuration:

[OperationContract] 
[WebGet(UriTemplate = "")] 
public List<ParentClass> GetParents() 
{ 
     using (DBContext context = new DBContext()) 
     {
         context.Configuration.ProxyCreationEnabled = false; 
         List<ParentClass> parents = context.Parents
             .Include("Children") 
             .ToList();
         return playlists; 
      }
}

这工作得很好了我。

这篇关于有父子关系时的WebAPI与EF code首先生成错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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