【问题标题】:Fetch foreign key table data获取外键表数据
【发布时间】:2018-09-16 10:01:31
【问题描述】:

从 dbcontext 获取数据时 this.dbcontext.JobDetails.GetAll()。 在这里,我还需要来自当前jobDetails 的外键表中的数据。

public class Like
{
    public int LikeId { get;  set; }
    public JobDetails JobDetails { get; set; }
    [ForeignKey("JobDetailFK")]
    public int JobDetailId { get; set; }
}
public class JobDetails
{
    [Key]
    public int JobDetailId { get; set; }
    public ICollection<Like> Likes { get; set; }
}

【问题讨论】:

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


【解决方案1】:

在 Entity Framework 6 中,您可以这样做:

using (DatabaseContext context = new DatabaseContext()) {
    return context.JobDetails.Include(x => x.Likes).ToList();
}

【讨论】:

  • 感谢您的回复。它适用于单个列表对象。但我的 JobDetails 中至少有两个。
  • 然后您应该使用 select 查找 ThenInclude 和多级包含,您应该能够在每个给定关系中获取数据
【解决方案2】:

要扩展提供的答案,您还可以获得多个列表甚至嵌套数据。

List<item> items = db.mainData
    .Where(x => x.parentId == id)
    .Include(x => x.moreData)
            .ThenInclude(acc => acc.field)
    .Include(x => x.evenMoreData)
            .ThenInclude(acc => acc.field)
    .ToList();

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 2022-10-14
    • 2015-11-09
    • 2019-03-30
    • 2020-01-27
    • 2015-04-11
    • 2021-01-30
    • 2021-11-07
    • 1970-01-01
    相关资源
    最近更新 更多