Linq IN in C# error - c#

I'm trying to do this:
myList = (from c in ipE.Cars
where (someListOfIntegers.Contains(idCar) && c.name == someName)
select c).ToList();
I'm getting the eror LINQ to Entities does not recognize the method 'Boolean Contains(Int32)' method, and this method cannot be translated into a store expression.
I tried with ANY, it still doesn't work. I got the error Unable to create a constant value of type 'Closure type'. Only primitive types ('such as Int32, String, and Guid') are supported in this context.
How to resolve this?

Unfortunately, you cant't use local collections in an EF query. You can work around it, by using the PredicateBuilder and translate the Contains operation manually in a sequence of ORs:
var predicate = PredicateBuilder.False<Car>();
foreach (int id in someListOfIntegers)
{
int temp = id;
predicate = predicate.Or (car => car.idCar == id);
}
myList = (from c in ipE.Cars
where predicate && c.name == someName)
select c).ToList();
Sidenote: I assume, that you have a typo in your question, because neither someListOfIntegers nor idCar are properties of your EF model you query. So i guess you want to query for Car.idCar?.
Otherwise you just could refactor the Contains completely out of the EF query.

You seem to be suggesting (comments) that idCar does not relate to any entities - in which case, don't do that in the query:
List<Car> list;
if(someListOfIntegers.Contains(idCar)) {
myList = (from c in ipE.Cars
where c.name == someName
select c).ToList();
} else {
myList = new List<Car>(); // no need to touch the DB
}

Seen the same myself: L2E uses a small set of commands - and there isn't a "Contains(Int32)" command.
If your lists are fairly small, then try adding ".AsEnumerable()", which will execute the T-SQL select statements and leave you with POCO objects which CAN use Contains.
e.g.
myList = (from c in ipE.Cars.AsEnumerable
where (someListOfIntegers.AsEnumerable().Contains(idCar)
&& c.name == someName)
select c)
.ToList();
Not sure if you need both AsEnumerables...try it out!

Related

C# Linq Group by Object

I have an issue of using group by in LINQ to SQL statement.
The cod I have is
var combinedItems = (from article in articles
join author in authors
on article.AuthorId equals author.Id into tempAuthors
from tempAuthor in tempAuthors.DefaultIfEmpty()
select new { article , author = tempAuthor});
var groups1 = (from combinedItem in combinedItems
group combinedItem by combinedItem.article into g
select g.Key).ToList();
var groups2 = (from combinedItem in combinedItems
group combinedItem by combinedItem.article.Id into g
select g.Key).ToList();
I tried to group in two different ways. The first way, I group by an object and the second way I just group by a field in one of the objects.
When I run groups1, I got an error saying need to evaluate in client side, while when I use groups2, it works all good. Can I ask what could be wrong? If I want to group by object, is there any way to do it?
In case you want to group by object, as you've not overridden Equals and GetHashCode() in your Article class or implemented IEqualityComparer<Article> you're just getting the default comparison, which checks if the references are equal. So what you need is something like this:
class GroupItemComparer : IEqualityComparer<Article>
{
public bool Equals(Article x, Article y)
{
return x.Id == y.Id &&
x.Name == y.Name;
}
public int GetHashCode(Article obj)
{
return obj.Id.GetHashCode() ^
obj.Name.GetHashCode();
}
}
And then you need to change your query to lambda expression:
var groups1 = combinedItems.GroupBy(c => c.article , new GroupItemComparer())
.Select(c => c.Key).ToList();
In case you got any exception regarding translation your method to SQL, you can use AsEnumerable or ToList methods before your GroupBy method, with this methods after data is loaded, any further operation is performed using Linq to Objects, on the data already in memory.
As others have pointed out, the GroupBy is using reference equality by default, and you could get around it by specifying one or more properties to group by. But why is that an error?
The whole point of the query is to translate your Linq query into SQL. Since object reference equality on the client can't be easily translated to SQL, the translator doesn't support it and gives you an error.
When you provide one or more properties to group by, the provider can translate that to SQL (e.g. GROUP BY article.Id), and thus the second method works without error.

LINQ to Entities does not recognize the method 'System.String ToString(Int32)'

Hi I am using a linq query which is throwing the error LINQ to Entities does not recognize the method 'System.String ToString(Int32)' method, and this method cannot be translated into a store expression.
List<string> resultMap = (from item in mapResult
select Convert.ToString(item.ResultDE)).ToList();
Error is throwing in this below statement
List<Result_DE> resultList = (from result in db.Result_DE
where result.IsActive == "1"
&& resultMap.Contains(Convert.ToString(Convert.ToInt32(result.ID)))
select result).ToList();
please tell me the proper way of writing this query.
You cannot use these conversion functions in a LINQ to Entities statement, they cannot be translated to SQL, you need to do the conversions in memory. But I don't think you need to do that at all.
If you were just using the resultMap to get your resultList, filtered by Results of which the Id is present in mapResult, do the following:
var resultList = db.Result_DE
.Where(r => r.IsActive == "1" && mapResult.Any(mr => mr.ResultDE == r.ID));
.ToList();
If mapResult is an in-memory collection, instead of an IQueryable that is attached to the db context, you need to do the following:
var resultIds = mapResult.Select(mr => mr.ResultDE).ToList();
var resultList = db.Result_DE
.Where(r => r.IsActive == "1" && resultIds.Contains(r.ID));
.ToList();
Before you call any method (e.g. ToString()), you need to convert LINQ to Object using AsEnumerable().
if your item.ResultDE and result.ID is variable type of Int32,
why don directly create a List<Int32> ?
List<Int32> resultMap = (from item in mapResult
select item.ResultDE).ToList<Int32>();
List<Result_DE> resultList = (from result in db.Result_DE
where result.IsActive == "1"
&& resultMap.Contains(result.ID)
select result).ToList<Result_DE>();
Use SqlFunctions.StringConvert instead of Convert.ToString.
A similar question was asked and answered here

linq join on guid and string column

I'm new to linq. I need to run a query that joins two columns (AnonymousUser.AnonymousId being uniqueidentifier and comment.UserId being nvarchar(100)), something like below:
using (CommentEntities db = new CommentEntities())
{
// filteredComments is a query that is not run until the next .ToList()
IQueryable<Comment> filteredComments = this.CommentGetList(...);
var query = from comment in filteredComments
// following line is the syntax error, because columns' types don't match
join user in db.AnonymousUsers on comment.UserId equals user.AnonymousId into gj
from userNull in gj.DefaultIfEmpty()
select new CommentWithName
{
Comment = comment,
UserId = comment.UserId,
FirstName = (userNull == null ? "" : userNull.Name),
LastName = "",
Email = (userNull == null ? "" : userNull.Email)
};
return query.ToList();
}
First I was happy writing the query with .ToString() ! As it turns out that entity framework doesn't know how to translate it to sql. The same is true for Guid.Parse(string). Also new Guid(string) cannot be used in linq to entities (only parameterless constructors allowed)!
So after searching, I found out it's not possible doing such thing in EF 4.0! I migrated my code to a stored procedure that I'm not really happy about it.
Is it possible to tell entity framework to use a CAST in SQL?
Is there any solutions to this problem? Is there any way that I can bring the logic in code?
NOTE: I meant to do it in one GO. Otherwise one possible solution is to get Entities from first table, and put the Ids in a list and get entities from second table.
call toList() before applying those methods. Like:
var Product = db.Products.Where(p => p.ProductId == Guid.Parse("B4E913F9-166C-49BA-AADE-6DB889D1756F")).Single();
Would throw a
c# LINQ to Entities does not recognize the method "System.Guid Parse" (System.String)' method, and this method cannot be translated into a store expression
But this works:
var Product = db.Products.ToList().Where(p => p.ProductId == Guid.Parse("B4E913F9-166C-49BA-AADE-6DB889D1756F")).Single()
p.s.: I think you will lose lazyloading but you can do eagerloading with .Include before calling .ToList().
If your list is object list you could convert it to the type which has Guid as identifier, first create new anonymous type and then filter it base on UserId, sure UserId which is of type int, wont include in join:
int output = 0;
var secondList = list.Where(x=>!int.TryParse(x.UserID, out output))
.Select(x=>new {Comment = x, ID = new Guid(x.UserID))
.ToList();
Now you could run your query on db by using secondList.

Not sure what i am doing wrong get error: Unable to cast the type 'System.Linq.IQueryable`1' to type 'System.Linq.IQueryable`1'

i have this query:
var model2 = (from p in context.ViewChatPeoples
where ((IQueryable<int>)(from q in context.ConversationPeoples
where !q.Deleted && q.PersonId == info.LoginID
select new { q.ConversationId })).Contains(p.ConversationId)
select p.ConversationId).Distinct().ToList();
in LINQ / C#, however it seems to produce the following error:
Unable to cast the type 'System.Linq.IQueryable`1' to type 'System.Linq.IQueryable`1'. LINQ to Entities only supports casting Entity Data Model primitive types.
makes zero sense, i just want to run an WHERE IN, but seem to have hit this hurdle that makes no sense what so ever !!!
thanks
and as an update here is the final working code using the given solution:
var model2 = (from p in context.ViewChatPeoples
where ((from q in context.ConversationPeoples
where !q.Deleted && q.PersonId == info.LoginID
select q.ConversationId)).Contains(p.ConversationId)
select p.ConversationId).Distinct().ToList();
select new { q.ConversationId } creates an anonymously typed object with a property ConversationId. The code creates an IQueryable<[anonymous type]> instead of an IQueryable< int>.
simply select q.ConversationId to get an IQueryable< int>.
I think it's because the return type of your subquery isn't IQueryable<int> but IQueryable<anonymousType>. Changing the select from select new { q.ConversationId } to select q.ConversationID should resolve (untested).

LINQ to Entity: using Contains in the "select" portion throws unexpected error

I've got a LINQ query going against an Entity Framework object. Here's a summary of the query:
//a list of my allies
List<int> allianceMembers = new List<int>() { 1,5,10 };
//query for fleets in my area, including any allies (and mark them as such)
var fleets = from af in FleetSource
select new Fleet
{
fleetID = af.fleetID,
fleetName = af.fleetName,
isAllied = (allianceMembers.Contains(af.userID) ? true : false)
};
Basically, what I'm doing is getting a set of fleets. The allianceMembers list contains INTs of all users who are allied with me. I want to set isAllied = true if the fleet's owner is part of that list, and false otherwise.
When I do this, I am seeing an exception: "LINQ to Entities does not recognize the method 'Boolean Contains(Int32)' method"
I can understand getting this error if I had used the contains in the where portion of the query, but why would I get it in the select? By this point I would assume the query would have executed and returned the results. This little ditty of code does nothing to constrain my data at all.
Any tips on how else I can accomplish what I need to with setting the isAllied flag?
Thanks
This poached from a previous answer...
Contains not supported.
IN and JOIN are not the same operator (Filtering by IN never changes the cardinality of the query).
Instead of doing it that way use the join method. It's somewhat difficult to understand without using the query operators, but once you get it, you've got it.
var foo =
model.entitySet.Join( //Start the join
values, //Join to the list of strings
e => e.Name, // on entity.Name
value => value, //equal to the string
(ModelItem ent, String str) => ent);//select the entity
Here it is using the query operators
var foo = from e in model.entitySet
join val in values on
e.Name equals val
select e;
Basically the entity framework attempts to translate your LINQ query into a SQL statement but doesn't know how to handle the Contains.
What you can do instead is retrieve your fleets from the database and set the isAllied property later:
var fleets = (from af in FleetSource
select new Fleet
{
fleetID = af.fleetID,
fleetName = af.fleetName,
userId = af.userId
}).AsEnumerable();
foreach (var fleet in fleets)
{
fleet.isAllied = (allianceMembers.Contains(fleet.userID) ? true : false);
}
Everyone above me is wrong!!! (No offense ...) It doesn't work because you are using the IList overload of "Contains" and not the IEnumerable overload of "Contains". Simply change to:
allianceMembers.Contains<int>(af.userID)
By adding the <int>, you are telling the compiler to use the IEnumerable overload instead of the IList overload.
var fleets = from af in FleetSource;
var x = from u in fleets.ToList()
select new Fleet
{
fleetID = u.fleetID,
fleetName = u.fleetName,
isAllied = (allianceMembers.Contains(u.userID) ? true : false)
}
calling ToList() on fleets the query is executed, later you can use Contains().

Categories