如何使用EF核心从相关表中获取数据?

时间:2019-02-06 11:16:42

标签: c# entity-framework-core

我正在研究Web项目,我使用代码优先方法在机器模型和实验模型之间创建了一对多关系。这是代码:

   public class Experiment
{

    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime CreationDateTime { get; set; }
    public string Path { get; set; }
    public string Description { get; set; }

    [ForeignKey("Machine")]
    public int MachineId { get; set; }
    public Machine Machine { get; set; }
}


 public class Machine
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public string Description { get; set; }

    public ICollection<Experiment> Experiments { get; set; }
}

我可以通过userId进行所有实验过滤:

  public async Task<IList<Experiment>> GetExperimentsAsync(int userId)
    {
        var experiments = await _experimentsDbContext.Experiments
                                .Where(x => x.UserId == userId)
                                .ToListAsync();

        return experiments; 
    }

但是我收到machine = null,我需要做的是获取通过userId过滤的实验列表,并包含相关的机器对象,但是我不能这样做。

2 个答案:

答案 0 :(得分:1)

您需要使用.Include()方法明确指定要加载相关数据。

请看看MS documentation

示例:

public async Task<IList<Experiment>> GetExperimentsAsync(int userId)
{
    var experiments = await _experimentsDbContext.Experiments
                            .Where(x => x.UserId == userId)
                            .Include(e => e.Machine)
                            .ToListAsync();

    return experiments; 
}

答案 1 :(得分:0)

尝试以下代码:

public async Task<IList<Experiment>> GetExperimentsAsync(int userId)
{
    var experiments = await _experimentsDbContext.Experiments
                            .Include(experiment => experiment.Machine)
                            .Where(x => x.UserId == userId)
                            .ToListAsync();
    return experiments; 
}