我遇到一些麻煩的ASP.NET Web API與模型之間的多對多關係。這裏是我的模型(我已經簡化爲簡潔起見):的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 { }
}
}
和我的相關型號1 API控制器摘錄:
public class Model1sController : ApiController
{
private ApplicationDbContext db = new ApplicationDbContext();
// GET: api/Model1s
public IQueryable<Model1> GetModel1s()
{
return db.Model1s;
}
...
}
當我瀏覽到/ API/model1s我弄了半天JSON嵌套錯誤,這裏是最內層的異常消息。
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"
}]
}]
你怎麼說話的數據庫? – BillRuhl
我不太確定。我用這個教程開始我的項目中,這樣可能會給我的問題的一些更清晰:https://docs.microsoft.com/en-us/azure/app-service-web/web-sites-dotnet-rest-service -aspnet-api-sql-database –
好的......新的問題。爲什麼你的模型是這樣設置的?它看起來每個都包含另一個列表...是你真正想要的嗎?這可能會導致你的問題。 – BillRuhl