1

I am using Entity Framework 5.

Below is my SQL Query which runs successfully:

Select person.pk 
from person, job
Where 
person.jobId= job.pk 
and 
job.Description = 'CEO'

I have changed the table and column names in the above query.

Now whenI am converting the above query to below LINQ:

from person in Context.Person
from job in Context.Job
where
  person.jobId== job.PK &&
  job.Description == "CEO"
select new {
  person.PK
};

But the above LINQ is giving me an exception:

Unable to create a constant value of type 'Models.Job'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.

The LINQ looks simple enough but I am not able to figure out as to what am I missing.

This might be duplicate, but all the questions similar to this one were different and none of them addressed this issue.

Any help would be appreciated.

Shakti Prakash Singh
  • 2,414
  • 5
  • 35
  • 59
  • 1
    I'm curious why don't you use join syntax for join: `from person in Context.Person join job in Context.Job on person.jobId equals job.PK where job.Description == "CEO" select new { person.PK }`? – Vlad May 29 '13 at 15:25
  • even better idea would be to define foreign keys and use navigational properties, so the joins will be automatically handled by the EF for you. – Vlad May 29 '13 at 15:31
  • I read some of the posts for cross joins and I believe this is the syntax they followed in [1](http://stackoverflow.com/questions/10670678/how-do-you-code-a-cross-join-in-linq), [2](http://stackoverflow.com/questions/4715744/sql-to-linq-conversion-with-cross-join) and [3](http://stackoverflow.com/questions/56547/how-do-you-perform-a-cross-join-with-linq-to-sql). I am not too good at SQL or LINQ for that matter. I guess I need to do more reading and practice. – Shakti Prakash Singh May 30 '13 at 07:07

1 Answers1

1

That SQL is performing a join, why aren't you performing one in your Linq?

Also, I'm not sure why you're projecting into an anonymous type if you only want one field, just select that field (will map to a List<T> where T is the type of your PK field).

Try this:

from person in Context.Person
join job in Context.Job on person.jobID equals job.PK
where job.Description == "CEO"
select person.PK;
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
  • Thanks a lot. This worked. I read some of the posts for cross joins and I believe this is the syntax they followed [1](http://stackoverflow.com/questions/10670678/how-do-you-code-a-cross-join-in-linq), [2](http://stackoverflow.com/questions/4715744/sql-to-linq-conversion-with-cross-join) and [3](http://stackoverflow.com/questions/56547/how-do-you-perform-a-cross-join-with-linq-to-sql). I am not too good at SQL or LINQ for that matter. I guess I need to do more reading and practice. – Shakti Prakash Singh May 30 '13 at 07:08