Aissam Aitkacem Aissam Aitkacem - 3 months ago 10
C# Question

Store Linq Query in a list c#

I have this class from my entity Framework, i want to store this result of my linq query in list to display it in my web form, i get this error message:


Error 4 Cannot implicitly convert type
'System.Collections.Generic.List' to
'System.Collections.Generic.List' \App_Code\Models\PackageModel.cs


this is my code:

thanks for a helping.

public partial class Package
{
public int ID { get; set; }
public int SchoolID { get; set; }
public int SessionID { get; set; }
public int LessonsID { get; set; }
public virtual Lesson Lesson { get; set; }
public virtual School School { get; set; }
public virtual Session Session { get; set; }
}

public List<Package> GetAllItemPackage()
{
try
{
using (MusicSchoolEntities db = new MusicSchoolEntities())
{
List<Package> packages = (from x in db.Packages
join y in db.Schools on x.SchoolID equals y.ID
join z in db.Sessions on x.SessionID equals z.ID
join w in db.Lessons on x.LessonsID equals w.ID
join q in db.Courses on w.CourseID equals q.ID
select new { SchoolTitle = y.TitleEn ,
SessionName = z.NameEn,
CourseTitle = q.TitleEn,
LessonPeriod = w.PeriodEn,
LessonPrice = w.PriceEn,
LessonDesc = w.DescriptionEn,
LessonPaymtd = w.PayMtdEn}).ToList();
return packages;
}
}

catch (Exception)
{
return null;
}
}

Answer

You have 2 problems there.

  1. First is that your code return an anonymous type but you are trying to populate a List<Package> - That is why you get the exception.
  2. Secondly, the data you are trying to populate isn't like the Package class that you have so if you want to return such a list from a function you should create a new type of class to have all those properties.

So:

List<YourClass> packages = (from x in db.Packages                                           
                          join y in db.Schools on x.SchoolID equals y.ID
                          join z in db.Sessions on x.SessionID equals z.ID
                          join w in db.Lessons on x.LessonsID equals w.ID
                          join q in db.Courses on w.CourseID equals q.ID
                          select new YourClass
                          {
                              SchoolTitle = y.TitleEn , 
                              SessionName = z.NameEn, 
                              CourseTitle = q.TitleEn, 
                              LessonPeriod = w.PeriodEn, 
                              LessonPrice = w.PriceEn, 
                              LessonDesc = w.DescriptionEn, 
                              LessonPaymtd = w.PayMtdEn
                          }).ToList();
return packages;

And of course GetAllItemPackage should return: List<YourClass> and not List<Package>

Comments