具有多个关系的ASP.NET Web API

时间:2017-02-22 21:35:38

标签: asp.net asp.net-mvc

我在ASP.NET Web API上遇到一些问题,模型之间有很多关系。这是我的模型(为简洁起见,我简化了):

public class Model1
{
    public int Model1ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Model2> Model2s{ get; set; }

    public string Self
    {
        get
        {
            return string.Format(CultureInfo.CurrentCulture,
                "api/model1/{0}", this.Model1ID);
        }
        set { }
    }
}

public class Model2
{
    public int Model2ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Model1> Model1s{ get; set; }

    public string Self
    {
        get
        {
            return string.Format(CultureInfo.CurrentCulture,
                "api/model2/{0}", this.Model2ID);
        }
        set { }
    }
}

和我的相关Model1 API控制器摘录:

public class Model1sController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET: api/Model1s
    public IQueryable<Model1> GetModel1s()
    {
        return db.Model1s;
    }

    ...
 }

当我导航到/ api / model1s时,我得到一个长JSON嵌套错误,这是最里面的Exception消息。

There is already an open DataReader associated with this Command which must be closed first.

我想要实现的是这样的输出,但我无法弄清楚如何让它工作。

[{
    "Model1ID": 1,
    "Name": "Some model 2 name",
    "Model2s": [{
        "Model2ID": 1,
        "Name": "Another model 2 name"
    }, {
        "Model2ID": 2,
        "Name": "Some model 2 name"
    }]
}, {
    "Model1ID": 2,
    "Name": "Another model 1 name",
    "Model2s": [{
        "Model2ID": 2,
        "Name": "Some model 2 name"
    }]
}]

0 个答案:

没有答案