gpt4 book ai didi

c# - ASP.NET 核心 : Preserve ForeignKey Relation in JsonResult

转载 作者:太空宇宙 更新时间:2023-11-03 22:56:05 26 4
gpt4 key购买 nike

当我使用不带外键的 JsonResult 从我的数据库 (EntityFramework) 发送一个对象时,我得到了我需要的结果。如果此对象包含 ForeignKey 关系,则该关系不在生成的 json 中:

我得到的:

{
"agentId":"9990447f-6703-11e7-9c8b-94de80ab7fee",
...
"configurationId": 22,
"configuration": null
}

我需要什么:

{
"agentId":"9990447f-6703-11e7-9c8b-94de80ab7fee",
...
"configurationId": 22,
"configuration": {
"id": 0,
...
}
}

What can i do to preserve this foreign key relation in my json?

我已经尝试设置以下内容:

services.AddMvc().AddJsonOptions(options => options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.All);

EF 上下文:

public class Agent
{
[Key]
public Guid AgentId { get; set; }
...
public int? ConfigurationId { get; set; }
[ForeignKey("ConfigurationId")]
public Configuration Configuration { get; set; }
}

public class Configuration
{
public int Id { get; set; }
...
public ICollection<Agent> Agents { get; set; }
}

Controller :

[HttpGet]
public JsonResult Index()
{
var agentList = _databaseContext.Agents;
return new JsonResult(agentList);
}

最佳答案

您可以加载 related data

[HttpGet]
public JsonResult Index()
{
var agentList = _databaseContext.Agents
.Include(agent=> agent.Configuration)
.ToList();;
return new JsonResult(agentList);
}

关于c# - ASP.NET 核心 : Preserve ForeignKey Relation in JsonResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45325006/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com