LINQ to EF Cross Join issue - linq

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.

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;

Related

Linq to Entities query non primitive type

I have this method I wrote as:
private void GetReceivedInvoiceTasks(User user, List<Task> tasks)
{
var taskList = from i in _db.Invoices
join a in user.Areas on i.AreaId equals a.AreaId
where i.Status == InvoiceStatuses.Received
select i;
}
Basically I was trying to get all the Invoices in the database in the user's area that have a status of received. I don't understand LINQ too well right now.
I'm getting the error:
base {System.SystemException} = {"Unable to create a constant value of
type 'Models.Area'. Only primitive types ('such as Int32, String, and
Guid') are supported in this context."}
Can someone please explain to me what I'm doing wrong and how to remedy this? I can't currently understand what the problem is. If I take the join line out it's fine but I really need that line to make sure I only have invoices from the users area/areas (they can belong to more than one area). Have I got something fundamentally wrong with this query?
Entity framework does not support joins with in-memory collections. You will have to re-wire your query to make use of a Contains query with a collection of primitives instead.
Also EF currently does not support enum values so you will have to compare with an integer value (If InvoiceStatuses.Received is not an enum value ignore this part).
Both fixes combined lead to the following query approach which should result in results equivalent to your join:
int statusReceived = (int)InvoiceStatuses.Received;
var areaIds = user.Areas.Select(x=> x.AreaId).ToArray();
var taskList = from i in _db.Invoices
where i.Status == statusReceived && areaIds.Contains(i.AreaId)
select i;

How to handle missing rows in a dependent table

I have two Sql Server tables accessed through Entity Framework 4. They are joined by a single key with 0 to 1 rows on the dependent side of the join. Here is my linq query.
var typeDtoList = from type in typeList
select (new DxStudioTypeDto(parent,
isChildrenLoadOnDemand,
businessFacade,
server,
database,
type.typeGuid,
type.typeName,
type.writerName,
type.managerName,
type.Reporting_Type.MRef_Status,
type.Reporting_Type.Exists_In_Drop));
Obviously, if the Reporting_Type returns zero rows, the linq expression throws a null reference exception on the last two parameters of the DxStudioTypeDto constructor:
type.Reporting_Type.MRef_Status,
type.Reporting_Type.Exists_In_Drop));
Is there a way to detect the absence of a Reporting_Type row and substitute a default string? DxStudioTypeDto is an immutable type, so I need all the parameters available when I instanciate a new object. Any other strategies for this situation?
Did you try this?
((type.Reporting_Type == null) ? "some default value" : type.Reporting_Type.MRef_Status)
I know sometimes the EF engine returns a "the provider does not support this operation" for this kind of thing, but it's worth a try.

LINQ Select to entity reference's reference?

I have a three entity hierarchy for telecommunications exchanges in an SQL Express database and I'm using the Entity Framework to run some LINQ queries on it.
Exchange is in a SubRegion which is in a Region. Obviously I also have an implicit Exchanges in Region relationship as well.
(Exchange) *...1 (SubRegion) *...1 (Region)
*.....................1
Sometimes the user wants to see all the exchanges in a region or in a sub-region. When I use the following LINQ query, I get an exception.
Data.Region region = regionComboBox.SelectedItem as Data.Region;
var esas = from esa in JITScheduleContainer.Exchanges
where esa.SubRegion.Region == region
select esa;
exchangeComboBox.Items.AddRange(esas.ToArray());
Exception:
Unable to create a constant value of
type 'CpasJitScheduler.Data.Region'.
Only primitive types ('such as Int32,
String, and Guid') are supported in
this context.
Is there anything in the EF model I need to do or some other way of reference a parent's parent object?
I forgot that I could use the int Id field to compare. Resulting LINQ statement:
Data.Region region = regionComboBox.SelectedItem as Data.Region;
var esas = from esa in Container.Exchanges
where esa.SubRegion.Region.Id == region.Id
select esa;
exchangeComboBox.Items.AddRange(esas.ToArray());

Is this linq query efficient?

Is this linq query efficient?
var qry = ((from member in this.ObjectContext.TreeMembers.Where(m => m.UserId == userId && m.Birthdate == null)
select member.TreeMemberId).Except(from item in this.ObjectContext.FamilyEvents select item.TreeMemberId));
var mainQry = from mainMember in this.ObjectContext.TreeMembers
where qry.Contains(mainMember.TreeMemberId)
select mainMember;
Will this be translated into multiple sql calls or just one? Can it be optimised? Basically I have 2 tables, I want to select those records from table1 where datetime is null and that record should not exist in table2.
The easiest way to find out if the query will make multiple calls is to set the .Log property of the data context. I typically set it to write to a DebugOutputWriter. A good example for this kind of class can be found here.
For a general way of thinking about it however, if you use a property of your class that does not directly map to a database field in a where clause or a join clause, it will typically make multiple calls. From what you have provided, it looks like this is not the case for your scenario, but I can't absolutely certain and suggest using the method listed above.

Entity Framework - "Unable to create a constant value of type 'Closure type'..." error

Why do I get the error:
Unable to create a constant value of type 'Closure type'. Only
primitive types (for instance Int32, String and Guid) are supported in
this context.
When I try to enumerate the following Linq query?
IEnumerable<string> searchList = GetSearchList();
using (HREntities entities = new HREntities())
{
var myList = from person in entities.vSearchPeople
where upperSearchList.All( (person.FirstName + person.LastName) .Contains).ToList();
}
Update:
If I try the following just to try to isolate the problem, I get the same error:
where upperSearchList.All(arg => arg == arg)
So it looks like the problem is with the All method, right? Any suggestions?
It looks like you're trying to do the equivalent of a "WHERE...IN" condition. Check out How to write 'WHERE IN' style queries using LINQ to Entities for an example of how to do that type of query with LINQ to Entities.
Also, I think the error message is particularly unhelpful in this case because .Contains is not followed by parentheses, which causes the compiler to recognize the whole predicate as a lambda expression.
I've spent the last 6 months battling this limitation with EF 3.5 and while I'm not the smartest person in the world, I'm pretty sure I have something useful to offer on this topic.
The SQL generated by growing a 50 mile high tree of "OR style" expressions will result in a poor query execution plan. I'm dealing with a few million rows and the impact is substantial.
There is a little hack I found to do a SQL 'in' that helps if you are just looking for a bunch of entities by id:
private IEnumerable<Entity1> getByIds(IEnumerable<int> ids)
{
string idList = string.Join(",", ids.ToList().ConvertAll<string>(id => id.ToString()).ToArray());
return dbContext.Entity1.Where("it.pkIDColumn IN {" + idList + "}");
}
where pkIDColumn is your primary key id column name of your Entity1 table.
BUT KEEP READING!
This is fine, but it requires that I already have the ids of what I need to find. Sometimes I just want my expressions to reach into other relations and what I do have is criteria for those connected relations.
If I had more time I would try to represent this visually, but I don't so just study this sentence a moment: Consider a schema with a Person, GovernmentId, and GovernmentIdType tables. Andrew Tappert (Person) has two id cards (GovernmentId), one from Oregon (GovernmentIdType) and one from Washington (GovernmentIdType).
Now generate an edmx from it.
Now imagine you want to find all the people having a certain ID value, say 1234567.
This can be accomplished with a single database hit with this:
dbContext context = new dbContext();
string idValue = "1234567";
Expression<Func<Person,bool>> expr =
person => person.GovernmentID.Any(gid => gid.gi_value.Contains(idValue));
IEnumerable<Person> people = context.Person.AsQueryable().Where(expr);
Do you see the subquery here? The generated sql will use 'joins' instead of sub-queries, but the effect is the same. These days SQL server optimizes subqueries into joins under the covers anyway, but anyway...
The key to this working is the .Any inside the expression.
I have found the cause of the error (I am using Framework 4.5). The problem is, that EF a complex type, that is passed in the "Contains"-parameter, can not translate into an SQL query. EF can use in a SQL query only simple types such as int, string...
this.GetAll().Where(p => !assignedFunctions.Contains(p))
GetAll provides a list of objects with a complex type (for example: "Function"). So therefore, I would try here to receive an instance of this complex type in my SQL query, which naturally can not work!
If I can extract from my list, parameters which are suited to my search, I can use:
var idList = assignedFunctions.Select(f => f.FunctionId);
this.GetAll().Where(p => !idList.Contains(p.FunktionId))
Now EF no longer has the complex type "Function" to work, but eg with a simple type (long). And that works fine!
I got this error message when my array object used in the .All function is null
After I initialized the array object, (upperSearchList in your case), the error is gone
The error message was misleading in this case
where upperSearchList.All(arg => person.someproperty.StartsWith(arg)))

Resources