无法隐式转换类型 'System.Collections.Generic.List<<匿名类型

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type

完整异常消息:

Cannot implicitly convert type 'System.Collections.Generic.List<<anonymous type: Schedular.API.Models.TaskSchedule schedule, Schedular.API.Models.Note note>>' to 'System.Collections.Generic.IList<Schedular.API.Models.TaskSchedule>'. An explicit conversion exists (are you missing a cast?) [Schedular.API]

public async Task<IList<TaskSchedule>> GetTaskSchedulesByUser(int UserId)
{           
    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(); 

    return userTaskSchedule;            
}

我认为 return 方法的类型需要更改,但我不确定要更改什么。

型号

parent table = taskSchedule

child table = 注释

备注型号

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

任务计划模型

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

我希望您的 TaskSchedule 看起来像:

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

    public List<Note> Notes { get; set; }  
}

(Note class 仍然会有一个 TaskSchedule 属性 - EF 可以推断 TS:N 是 1:M 因为 rel 的一端是一个属性,另一端是一个集合)

要获取任务计划及其注释,您可以例如说:

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

    return userTaskSchedule;            
}

有关 how to configure relationships and also how to query related data

的大量信息