简体   繁体   中英

Retrieve data from child table using parent table LINQ query

I need to retrieve data from a child table. The parent table has a one to many relationships with the child table.

parent table = taskSchedule

child table = notes

Notes model

public class Note
{
    public int Id { get; set; }
    public string NotesInfo { get; set; }
    public DateTime dateCreated {get; set;}
    public TaskSchedule taskSchedule {get; set;}
    public User user { get; set; }
    public int userId { get; set; } 
}

TaskSchedule Model

public class TaskSchedule
{
    public int Id { get; set; }
    public string Title { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public User user { get; set; }
    public int userId { get; set; }     
}

I need to be able to return back all the notes connected to a specific task. Furthermore, I need to return back only the tasks related to a specific user.

The current code returns back the tasks related to a specific user.

       public async Task<IList<TaskSchedule>> GetTaskSchedulesByUser(int UserId)
    {
        var userTaskSchedule = await _context.TaskSchedules
            .Where(u => u.userId == UserId)
            .ToListAsync();                                   

        return userTaskSchedule;            
    }

I need to be able to return back the notes related to those tasks as well.

Would a simple inner join suit your needs here? (untested, but this is the general idea behind a LINQ inner join)

var userTaskSchedule = await _context.TaskSchedules
.Join(_context.Notes, schedule => schedule.Id, note => note.Id, (schedule, note) => new { schedule, note })
.Where(u => u.schedule.userId == UserId)
.ToListAsync();  

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