How to get data from related table with EF core?

c# entity-framework-core

Question

I'm working on web project, I created one-to-many relationship with code-first approach, between machine model and experiment model. Here is the code:

   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; }
}

I can take all of the experiments filter by userId:

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

        return experiments; 
    }

But I receive machine = null, what I need to do is get list of experiments filter by userId and include related machine object, but I can't do this.

1
1
2/6/2019 11:16:42 AM

Popular Answer

You need to explicitly specify that you want to load related data by using the .Include() method.

Please have a look at the MS documentation

Example:

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
2/6/2019 11:39:37 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow