GolfBravo
GolfBravo

Reputation: 1117

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

Full exception message:

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

I believe the return type of the method needs changing but I am not sure to what.

Models

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

Upvotes: 1

Views: 1762

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

I'd expect your TaskSchedule to look like:

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

(The Note class would still have a single TaskSchedule property - EF can infer that TS:N is 1:M as a result because one end of the rel is a single property and the other end is a collection)

And to get task schedules and their notes you could e.g. say:

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

Bucketloads of info on how to configure relationships and also how to query related data

Upvotes: 2

Related Questions