c# - Entity Framework 返回 "$ref"项

标签 c# entity-framework

我正在做作业 - 使用 Entity Framework 制作一个 Web api 2 项目。

这是我的表格布局,Singer 和 Genre 表之间有 m-2-m 关系。

enter image description here

我的流派是一个表,我用它按字母顺序获取歌手列表(因此流派表获取从(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)而不返回所有列其他关系数据(播放列表、歌曲、视频...)?

enter image description here

最佳答案

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/

相关文章:

c# - 重定向到错误页面并显示用户友好错误

c# - .NET Core 中 [Serializable] 的等价物是什么? (转换项目)

c# - 以编程方式添加 Adomd 参数 C#

c# - 如何使用 EF 在 ASP.NET MVC 中自动创建数据库和存储库?

.net - Entity Framework 错误 - "The EntityContainer name must be unique"

c# - 类似于 jQuery UI Draggables 的免费 Windows 窗体组件

c# - 如何决定每个用户状态的存储位置?注册表?应用程序数据?隔离存储?

c# - Entity Framework Core 2.0 中的迁移 - 如何指定环境或传递参数

c# - 数据库已创建,未添加新表

entity-framework - EF Core 工具版本更新 2.1.1