The entity or complex type 'xxx' cannot be constructed in a LINQ to Entities query?
-
20-06-2021 - |
Question
Model
public partial class SayacOkumalariIstatistik
{
public string sno { get; set; }
public Nullable<System.DateTime> okuma_tarihi { get; set; }
public Nullable<decimal> TotalUsageValue { get; set; }
public string UsageType { get; set; }
}
function
public IList<SayacOkumalariIstatistik> SayacOkumalariGetir()
{
#region linq concat
IEnumerable<SayacOkumalariIstatistik> sayac_okumalari_istatistik = entity.TblSayacOkumalari
.Select(x => new SayacOkumalariIstatistik
{
sno = x.sno.ToString() + "T1",
okuma_tarihi = x.okuma_tarihi,
TotalUsageValue = x.toplam_kullanim_T1,
UsageType = "T1"
})
.Concat(entity.TblSayacOkumalari.Select(x => new SayacOkumalariIstatistik
{
sno = x.sno.ToString() + "T2",
okuma_tarihi = x.okuma_tarihi,
TotalUsageValue = x.toplam_kullanim_T2,
UsageType = "T2"
}))
.Concat(entity.TblSayacOkumalari.Select(x => new SayacOkumalariIstatistik
{
sno = x.sno.ToString() + "T3",
okuma_tarihi = x.okuma_tarihi,
TotalUsageValue = x.toplam_kullanim_T3,
UsageType = "T3"
}));
#endregion
// Error occurs in here
return sayac_okumalari_istatistik.ToList();
}
And Error message is my question title. Why this error occur.
Thanks.
Solution
The error message is self-explanatory. You can't and shouldn't use your entity classes as projection DTOs (I'm guessing SayacOkumalariIstatistik
is such a class)
You have at least 3 alternatives:
- Retrieve the original entities first, then do the projections using Linq to objects (i.e. after the
ToList
call). - Create a DTO class (
SayacOkumalariIstatistikViewModel
,SayacOkumalariIstatistikDTO
, whatever) and use that in your query. - Use anonymous objects for the projection.
OTHER TIPS
This was done so that there is a clear distinction/break point between Linq to Entities and Linq to objects. In Linq to Sql you could easily be doing large operations in memory rather than in the database without having any idea the code was going to do that.
You have to return only anonymous types, primitives, Entity types, or a combination of the three.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow