【问题标题】:asp.net core: Preserve ForeignKey Relation in JsonResultasp.net 核心:在 JsonResult 中保留外键关系
【发布时间】:2017-07-26 11:00:50
【问题描述】:

当我使用没有外键的 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,
        ...
    }
}

我可以做些什么来在我的 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; }
}

控制器:

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

【问题讨论】:

    标签: c# json asp.net-core entity-framework-core


    【解决方案1】:

    您可以加载related data

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

    【讨论】:

    • 这个“有点”有效,我在我的 json 中获取了配置对象。问题是,我只得到第一个代理对象,而不是所有代理的列表。
    • 澄清一下,我可以看到 linq 返回多个代理,但生成的 json 只包含一个。
    • 我发现了问题。 PreserveReferencesHandling.All 仍然需要,否则包含将不起作用。我刚改成PreserveReferencesHandling.Object
    猜你喜欢
    • 2021-12-31
    • 1970-01-01
    • 2020-03-21
    • 1970-01-01
    • 2020-07-08
    • 2022-01-04
    • 1970-01-01
    • 2021-11-09
    • 2011-04-28
    相关资源
    最近更新 更多