【问题标题】:Embed Foreign Key Objects in JSON Response in .NET在 .NET 的 JSON 响应中嵌入外键对象
【发布时间】:2015-02-23 20:54:36
【问题描述】:

我想在我的 API 中将外键对象嵌入到我的 .NET JSON 响应中。我来自 Rails 背景,格式化 JSON 响应以包含任何找到的外键记录非常简单。但是,我似乎找不到这样做的方法。我有一个外键关系设置如下模型:

public class Person
{
[Key]
public int id {get; set;}
public string name {get; set;}
}

public class House
{
[Key]
public int id {get; set;}
public string address {get; set;}
[Required]
public int personId {get; set;}
[ForeignKey("peronsId")]
public Person person {get; set;}
}

但是,当我运行 GET 请求时,我得到的房子是这样的:

{
"id":1,
"address":"Middle of Nowhere",
"personId":3
}

当我想要的是:

{
"id":1,
"address":"Middle of Nowhere",
"person":{
"id":3,
"name":"Some Dude"
}
}

或一些类似的结构。如何在 .NET 中完成此操作?

在 C# 中将 .NET 4.5 Web API 2 与实体框架结合使用。

【问题讨论】:

    标签: c# .net json entity-framework foreign-keys


    【解决方案1】:

    尝试制作导航属性virtual:

    public class House
    {
      //...
      [ForeignKey("peronsId")]
      public virtual Person person {get; set;}
    }
    

    如果您没有禁用延迟加载行为,EF 会在取消引用该实体的导航属性时自动加载相关实体。

    另一个选项是使用 Include 扩展方法预先加载导航属性:

    datacontext.Houses.Include(h=>h.person);
    

    我建议您查看此link 以了解有关此主题的更多信息

    【讨论】:

      猜你喜欢
      • 2013-04-29
      • 2019-07-08
      • 2020-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      相关资源
      最近更新 更多