1

So I have a LINQ query below:

var data= (from p in _db.P
           join t in _db.TP on
           p.Id equals t.PId
           select
                  new TPE{
                           PId= t.PId,
                           TId= t.Id
                          }
            ).ToList();

            return data;

But when I run it, it gives me an error:

The entity or complex type 'TPE' cannot be constructed in a LINQ to Entities query. 

I've looked at other LINQ queries that do exactly this, but I don't know why my query isn't working. Any insight?

nirmus
  • 4,913
  • 9
  • 31
  • 50
Jay Sun
  • 1,583
  • 3
  • 25
  • 33

1 Answers1

6

The simplest approach here is to fetch into an anonymous type and then do the rest in-process via AsEnumerable:

return (from p in _db.P
        join t in _db.TP on p.Id equals t.PId
        select new { t.PId, t.Id }).AsEnumerable()
       .Select(x => new TPE { PId = x.PId, TId = x.Id })
       .ToList();

Or all in extension method syntax:

return _db.P.Join(_db.TP, p => p.Id, t => t.PId,
                 (p, t) =>  new { t.PId, t.Id })
            .AsEnumerable()
            .Select(x => new TPE { PId = x.PId, TId = x.Id })
            .ToList();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Ah, that works. Thanks a lot! Also, I found out what my problem was. I was mapping it to an Entity Framework object and apparently you can't do that in ADO.NET. See http://stackoverflow.com/questions/5325797/the-entity-cannot-be-constructed-in-a-linq-to-entities-query – Jay Sun Aug 10 '11 at 15:30