简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM