我正在做作业 - 使用 Entity Framework 制作一个 Web api 2 项目。
这是我的表格布局,Singer 和 Genre 表之间有 m-2-m 关系。
我的流派是一个表,我用它按字母顺序获取歌手列表(因此流派表获取从(ID:1,名称:“A”)到(ID:26,名称:“Z”)的数据
现在我想让所有歌手都以“H”开头(id=8)
public IQueryable<Singer> GetByGenre(int id)
{
return db.Singers.Where(s => s.Genres.Any(g => g.ID == id));
}
使用此查询:
http://localhost:6798/api/Singers/GetByGenre?id=8
但是结果很奇怪 - 只有第一个结果显示,而其他结果作为“ref”返回?我通过创建一个“假”列表进行检查
var list = db.Singers.Where(s => s.Genres.Any(g => g.ID == id)).ToList();
并对其进行调试,它会返回正确的 3 Singers ?
--
正如你所看到的,我有其他表(歌曲、播放列表、视频),它们有一个 FK 指向我的 Singer 的 ID,所以我怎样才能只返回 Singer 表的列(ID、NAME、IMAGE)而不返回所有列其他关系数据(播放列表、歌曲、视频...)?
最佳答案
Why does it include $ref in returned json result.
Json 序列化器包含 $ref 来解决循环依赖。
在此处查看有关此 Stackoverflow 答案的详细信息 -> Why is the Web Api returning empty json results with “$ref=”?
how can I only return the Singer table's columns only (ID, NAME, IMAGE) without all other relationship data ( Playlists, Songs, Videos ...) ?
您需要在 Entity Framework dbcontext 中禁用延迟加载。
像这样:
db.Configuration.LazyLoadingEnabled = false;
有关延迟加载和序列化程序的更多信息,请详细查看 this msdn 文章。
关于c# - Entity Framework 返回 "$ref"项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30342596/