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;
}
}
You have 2 problems there.
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.
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>
Related
i have a question, i want to create a linq query that returns a list of object.
This is the model
public class Test
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(5)]
public string Code { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[NotMapped]
public string Reference { get; set; }
}
The query that i want to do is simple: context.Test.ToList();
this returns the database mapping Reference is null since is not part of the table.
Now if i create a linq query i know that i can do select new { all fields here }
i want to avoid this:
select new Test
{
Reference = r,
ID = t.ID,
Code = t.Code,
Name = t.Name
}).ToList();
is it possible to do something like this
(from t in context.Test
join r in context.Reference on f.ID equals r.ID
select new
{
t.Reference = r.Reference,
t
}).ToList();
i want to set the Reference value inside the same query, is that possible?
What are you asking is not directly supported in LINQ to Entities - neither projection to entity type, nor expression block which is the only way to assign properties of an existing object.
As usual, the typical workaround is to split the query on two parts - one being LINQ to Entities query selecting the necessary data (usually into intermediate anonymous type), then switch to LINQ to Objects with AsEnumerable() and do the rest - in this case using block inside Select:
var result =
(from t in context.Test
join r in context.Reference on f.ID equals r.ID
select new { t, r.Reference }
).AsEnumerable()
.Select(x =>
{
x.t.Reference = x.Reference;
return x.t;
}).ToList();
Don't select an anonymous object, just create a new T from the one you have.
(from t in context.Test
join r in context.Reference on t.ID equals r.ID
select new Test
{
Reference = r,
ID = t.ID,
Code = t.Code,
Name = t.Name
}).ToList();
EDIT:
To avoid having to manually copy over all the properties
public class Test
{
public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Reference { get; set; }
public Test CopyWithReference(string reference)
{
var copy = (Test)this.MemberwiseClone();
copy.Reference = reference;
return copy;
}
}
Then...
(from t in context.Test
join r in context.Reference on t.ID equals r.ID
select t.CopyWithReference(r)).ToList();
Try following :
(from t in context.Test
join r in context.Reference on f.ID equals r.ID
select new Test()
{
ID = t.ID,
Code = t.Code,
Name = t.Name,
Reference = r.Reference
}).ToList();
Try:
var result = context.Test.Include("Reference").ToList();
or:
var result = context.Test.Include(t => t.Reference).ToList();
or Try Lambda Expressions:
var result = context.Test.Select(t => new {
t,
t.Reference = t.Reference.Select(r => new {
r.Reference })
}).AsEnumerable().Select(x => x.r).ToList();
can anyone please tell me, I have already joined five tables and I have tested join is correct. When I debug up to "Location1" values return.
Also I added return Location1, It says
"Error 1 Cannot implicitly convert type
'System.Collections.Generic.List' to
'System.Collections.Generic.IEnumerable'.
An explicit conversion exists (are you missing a cast?)"
My question is how can I display return valve?
This is my ApiController and class code.
public class Posts
{
public Suburb suburb { get; set; }
public SubRegion subRegion { get; set; }
public SubRegionDeliveryTime subRegionDeliveryTime { get; set; }
public DeliveryTime deliveryTime { get; set; }
public DeliveryPeriod deliveryPeriod { get; set; }
}
public IEnumerable<Posts> Get()
{
using (ApplicationDbContext db = new ApplicationDbContext())
{
var Location1 = (from su in db.TLCSuburb
join Subr in db.TLCSubRegion on
su.SubRegionID equals Subr.SubregionID
join srdt in db.TLCSubRegionDeliveryTime on
Subr.SubregionID equals srdt.SubregionID
join DT in db.TLCDeliveryTime on
srdt.DeliveryTimeId equals DT.DeliveryTimeId
join DP in db.TLCDeliveryPeriod on
DT.DeliveryPeriodID equals DP.DeliveryPeriodID
orderby Subr.SubregionID
select new
{
su.name,
su.postcode,
su.AuState,
su.Latitude,
su.Longitude,
DT.DeliveryDay,
DP.PeriodType,
Subr.CloseDayId,
Subr.SubregionName,
}).ToList();
//return null;
return Location1;
}
}
Write like this:
var Location1 = (from su in db.TLCSuburb
join Subr in db.TLCSubRegion on
su.SubRegionID equals Subr.SubregionID
join srdt in db.TLCSubRegionDeliveryTime on
Subr.SubregionID equals srdt.SubregionID
join DT in db.TLCDeliveryTime on
srdt.DeliveryTimeId equals DT.DeliveryTimeId
join DP in db.TLCDeliveryPeriod on
DT.DeliveryPeriodID equals DP.DeliveryPeriodID
orderby Subr.SubregionID
select new Post
{
suburb = new Suburb(){
Name = su.name,
PostCode = su.postcode,
AuState = su.AuState,
Latitude = su.Latitude,
Longitude = su.Longitude
},
deliveryTime = DT.DeliveryDay,
deliveryPeriod = new DeliveryPeriod(){
PeriodType = DP.PeriodType
},
subRegion = new SubRegion(){
CloseDayId = Subr.CloseDayId,
SubRegionName = Subr.SubregionName
}
}).ToList();
You'll have to explicitly convert it to IEnumerable<Post> instead of an anonymous type.
I have simple sql Left join query as:
select a.firstName+' '+a.lastName Name from account a left join
EH_PP_TeacherEvaluations b
on a.id=b.EH_PP_TE_TeacherAcctID
I wanted to do it in linq.
I tried to do it as follows:
List<Entity.TeacherEval> list = new List<Entity.TeacherEval>();
list = (from a in context.accounts join b in context.EH_PP_TeacherEvaluations on
a equals b.EH_PP_TE_TeacherAcctID into te
from b in te.DefaultIfEmpty()
select new { a.firstName+' '+a.lastName}
).ToList();
return list;
But its not working.
Error on 'join' :
Type interface failed in call to Group join.
and on row:
select new { a.firstName+' '+a.lastName}
Please help me.
Where i am making mistake, i am new with linq.
Edit 1 :
public class TeacherEval
{
public Guid ID { get; set; }
public DateTime? ProcessStartDate { get; set; }
public DateTime? ProcessEndDate { get; set; }
public Guid? AccountID { get; set; }
public Guid? StatusId { get; set; }
public TeacherEval() { }
public TeacherEval(DB.EH_PP_TeacherEvaluation item)
{
this.ID = item.EH_PP_TE_TeacherEvalID;
this.ProcessStartDate = item.EH_PP_TE_TeacherEvalProcessStartDate;
this.ProcessEndDate = item.EH_PP_TE_TeacherEvalProcessEndDate;
this.AccountID = item.EH_PP_TE_TeacherAcctID;
this.StatusId = item.EH_PP_TESRT_TeacherEvalStatusIDEH;
}
public DB.EH_PP_TeacherEvaluation ToDB()
{
var rec = new DB.EH_PP_TeacherEvaluation();
rec.EH_PP_TE_TeacherEvalProcessStartDate = this.ProcessStartDate;
rec.EH_PP_TE_TeacherEvalProcessEndDate = this.ProcessEndDate;
rec.EH_PP_TE_TeacherAcctID = this.AccountID;
rec.EH_PP_TESRT_TeacherEvalStatusIDEH = this.StatusId;
return rec;
}
public DB.EH_PP_TeacherEvaluation ToDB(DB.EH_PP_TeacherEvaluation rec)
{
rec.EH_PP_TE_TeacherEvalProcessStartDate = this.ProcessStartDate;
rec.EH_PP_TE_TeacherEvalProcessEndDate = this.ProcessEndDate;
rec.EH_PP_TE_TeacherAcctID = this.AccountID;
rec.EH_PP_TESRT_TeacherEvalStatusIDEH = this.StatusId;
return rec;
}
}
Try this:
var result= (
from a in context.accounts
from b in context.EH_PP_TeacherEvaluations
.Where(w=>w.EH_PP_TE_TeacherAcctID == a.id).DefaultIfEmpty()
select new {name= a.firstName+" "+a.lastName}
).ToList();
This will be translate to a LEFT JOIN
Edit
It looks to me like you want to fill a new object. Do I would suggest you doing something like this:
public class ResultDTO
{
public string Name { get; set; }
}
And then the query like this:
var result= (from a in context.accounts
join b in context.EH_PP_TeacherEvaluations on
a.id equals b.EH_PP_TE_TeacherAcctID
into te
from b in te.DefaultIfEmpty()
select new ResultDTO
{
Name= a.firstName+" "+a.lastName
}
).ToList();
This will result into a List<ResultDTO>
Edit 2
Alternative you can also do this. If you just want the string:
var result= (from a in context.accounts
join b in context.EH_PP_TeacherEvaluations on
a.id equals b.EH_PP_TE_TeacherAcctID
into te
from b in te.DefaultIfEmpty()
select a.firstName+" "+a.lastName
).ToList();
This will result into a List<string>
do like this:
List<Entity.TeacherEval> list = (from a in context.accounts
join b in context.EH_PP_TeacherEvaluations
on a.id equals b.EH_PP_TE_TeacherAcctID into te
from b in te.DefaultIfEmpty()
select new Entity.TeacherEval
{Name = a.firstName+" "+a.lastName}).
ToList<Entity.TeacherEval>();
Your class should have property of Name:
public class TeacherEval
{
public string Name {get;set;}
}
Try this:
List<Entity.TeacherEval> list = (from a in context.accounts join b in
context.EH_PP_TeacherEvaluations on
a.id equals b.EH_PP_TE_TeacherAcctID into te
from b in te.DefaultIfEmpty()
select new Entity.TeacherEval { Name = a.firstName+' '+a.lastName}
).ToList();
You need to add a Property called Name in the class Entity.TeacherEval
OR
you can simply call the list into a variable like this
var list = (from a in context.accounts join b in
context.EH_PP_TeacherEvaluations on
a.id equals b.EH_PP_TE_TeacherAcctID into te
from b in te.DefaultIfEmpty()
select new { Name = a.firstName+' '+a.lastName}
).ToList();
Hi I have following two model classes
public class c1
{
public int id { get; set; }
public int ptId { get; set; }
public int bId { get; set; }
public int rId { get; set; }
public IEnumerable<styles> newStruct { get; set; }
}
public class styles
{
public int id { get; set; }
public int bId { get; set; }
public string desc { get; set; }
}
I am trying to write a linq query
var records = (from y in db.main
join c in db.secondary on y.bId equals c.bId
where c.id == id
select new c1
{
pId= c.pId,
id = c.id,
newStruct = new List<styles>
{
new styles
{
id=y.room_id,
desc=y.desc,
}
}
});
return records.ToList();
Problem I am having is that in newStruct is suppose to be List of all the styles but it just returns one style at a time rather than one list.
Please let me know how can it return record where inside it contains list of styles
Thanks
If you want to get a sublist by main list, you should use group by,
You can try this, but I'm not sure it worked. Becasue I couldn't compile it.
var records = (from y in db.main
join c in db.secondary on y.bId equals c.bId
where c.id == id
group c by new
{
c.pId,
c.id
} into gcs
select new c1
{
pId = c.Key.pId,
id = c.Key.id,
newStruct = from g in gcs select new styles { id=g.room_id, desc=g.desc}
});
Is this LINQ to Entities? If so, and the mappings are correct in the edmx, you can try:
var records =
from c in db.secondary
where c.id == id
select new c1
{
pId = c.pId,
id = c.id,
newStruct = c.main.Select(m => new styles { id = m.room_id, desc = m.desc })
};
return records.ToList();
I have a linq query, which is further having a subquery, I want to store the result of that query into a user defined type, my query is
var val = (from emp in Employees
join dept in Departments
on emp.EmployeeID equals dept.EmployeeID
select new Hello
{
EmployeeID = emp.EmployeeID
Spaces = (from order in Orders
join space in SpaceTypes
on order.OrderSpaceTypeID equals space.OrderSpaceTypeID
where order.EmployeeID == emp.EmployeeID group new { order, space } by new { order.OrderSpaceTypeID, space.SpaceTypeCode } into g
select new
{
ID = g.Key.SpaceTypeID,
Code = g.Key.SpaceTypeCode,
Count = g.Count()
})
}).ToList();
Definition for my Hello class is
public class Hello
{
public IEnumerable<World> Spaces { get; set; }
public int PassengerTripID { get; set; }
}
Definition for my World class is
public class World
{
public int ID { get; set; }
public string Code { get; set; }
public int Count { get; set; }
}
You are creating anonymous object but you need to specify type name World
select new World
{
ID = g.Key.SpaceTypeID,
Code = g.Key.SpaceTypeCode,
Count = g.Count()
})