rkaminski
rkaminski

Reputation: 39

How to get data from related table with EF core?

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.

Upvotes: 1

Views: 4272

Answers (2)

Bijay Yadav
Bijay Yadav

Reputation: 958

Try the below code:

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

Upvotes: 0

Janus Pienaar
Janus Pienaar

Reputation: 1103

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

Upvotes: 2

Related Questions