Home > Software design >  Cannot implicitly convert WebApi
Cannot implicitly convert WebApi

Time:12-30

I am working on a challenge and I have an error I cannot figure out. It says "Cannot implicitly convert type 'HolidayChallenge.Models.Ornament.Ornament2ListItem[]' to 'System.Collections.Generic.IEnumerable<HolidayChallenge.Data.Ornament2> I am not at all sure how to fix this. The error is on the return query.ToArray(); line.

public IEnumerable<Ornament2> GetOrnaments()
        {
            using (var ctx = new ApplicationDbContext())
            {
                var query =
                    ctx
                        .Ornaments
                        .Where(e => e.UserId == _userId)
                        .Select(
                            e =>
                                new Ornament2ListItem
                                {
                                    Id = e.Id,
                                    Description = e.Description,
                                    TreeId = e.TreeId
                                }
                                );
                return query.ToArray();
            }
        }

The code for the Ornament2ListItem follows:

namespace HolidayChallenge.Models.Ornament
{
    public class Ornament2ListItem
    {
        [Key]
        public int Id { get; set; }
        public string Description { get; set; }
        public virtual List<Ornament2> Ornaments { get; set; }
        public int TreeId { get; set; }
    }
}

The code for the Data layer follows:

namespace HolidayChallenge.Data
{
    public class Ornament2
    {
        [Key]
        public int Id { get; set; }
        public Guid UserId { get; set; }
        public string Description { get; set; }
        public virtual List<Ornament2> Ornaments { get; set; }
        [ForeignKey("ChristmasTree")]
        public int TreeId { get; set; }
        [Required]
        public virtual ChristmasTree ChristmasTree { get; set; }
    }
}

I would appreciate any help with this.

CodePudding user response:

Please relpace queary.ToArray() to query.ToList(); Also change return type IEnumerable to IEnumerable

CodePudding user response:

The problem is that your query is projecting the results into an IEnumerable of the type Ornament2ListItem ...

.Select(
    e =>
        new Ornament2ListItem
        {
            Id = e.Id,
            Description = e.Description,
            TreeId = e.TreeId
        }
        );

but the expected return type is IEnumerable of Ornament2 ...

public IEnumerable<Ornament2> GetOrnaments()

If you really want to return an IEnumerable of Ornament2ListItem then you need to change the return type of the method ...

public IEnumerable<Ornament2ListItem> GetOrnaments()

If you want to return an IEnumerable of Ornament2, then just return that from the context, instead of projecting into Ornament2ListItem ...

return
    ctx
        .Ornaments
        .Where(e => e.UserId == _userId);
  •  Tags:  
  • c#
  • Related