Linq error - "NotSupportedException: Unsupported overload used for query operator 'Select'" - linq

I have the following Linq query:
var tmp =
from container in Container
join containerType in ContainerType on container.ContainerType equals containerType
where containerType.ContainerTypeID == 2
select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID};
var results = tmp.Select((row, index) => new { row.ContainerID, row.TypeID, ContainerIndex = index })
As is, this works fine. If I add the following, so I can see the results in LinqPad, I get the error described in the title of this message:
results.Dump();
This error is not a LinqPad error, it's coming from Linq, and I don't understand what it means.
Thank you.

Okay, I hadn't realised Container was a LINQ to SQL data source to start with. Basically it's failing to convert the second projection to SQL.
So, you want to do just that bit in .NET instead - you can force it to use Enumerable.Select with AsEnumerable:
var results = tmp.AsEnumerable()
.Select((row, index) => new { row.ContainerID, row.TypeID,
ContainerIndex = index });

Related

Linq Query Message: Specified cast is not valid

Following are the columns name and its data type:
TemplateName string
TaskName string
AvgDays string (but contains int values)
my LINQ query:
DataTable newTable = new DataTable();
newTable = (from r in table.AsEnumerable()
group r by r.Field<string>("TemplateName") into templates
let totalDays = templates.Sum(r => r.Field<int>("AvgDays"))
from t in templates
group t by new
{
TemplateName = templates.Key,
TaskName = t.Field<string>("TaskName"),
TotalDays = totalDays
} into tasks
select new
{
tasks.Key.TemplateName,
tasks.Key.TaskName,
AvgDays = tasks.Sum(r => r.Field<int>("AvgDays")),
tasks.Key.TotalDays
}).CopyToDataTable();
I am getting error after execution of query. Error is "Specified cast is not valid.".
Please let me know where am I doing wrong.
I guess Field<int> causes the problem, because the field is not really an int. As you said before, it's a string.
Try following
AvgDays = tasks.Sum(r => int.Parse(r.Field<string>("AvgDays"))),
Field<T> does not perform some magic transformation between different types. It's implemented like that:
return (T)((object)value);
In practice there is a little bit more code, but logic is the same. It just tried to cast your value to desired type, and as you probably know, casting string to int does not work.

mvc3 dapper No mapping exists from model

I am doing some coding in dapper and I get the error No mapping exists from object type to a known managed provider native type this error occurs on the myfriends var for dapper . I am using dapper to get a list of INT values from a table then comparing them against another.. this is the code that gives me that error
int myid = Convert.ToInt32(User.Identity.Name);
// The var myfriend is giving me that error above
var myfriends = sqlConnection.Query<friend>("Select otherfriendsID from friends where profileID=#myidd", new { myidd = myid }).ToList();
var profiles = sqlConnection.Query<profile>("Select top 40 * from profiles where photo is not null AND profileID=#friendship order by profileID desc", new {friendship=myfriends}).ToList();
however if I use entity everything works fine for instance this code below works..
var myfriends = (from s in db.friends where s.profileID == myid select s.otherfriendsID).ToList();
What could be going on here..
myfriends is a List<friend>. You then pass that in as a query parameter, i.e.
new {friendship=myfriends}
with:
AND profileID=#friendship
Now... what is #friendship ? How should it pass in a List<friend> here? What does that even mean to pass in a list of objects (each of which could have multiple properties) as a single parameter? (note: I'm ignoring table-valued-parameters for the purposes of this question)
So: how many myfriends do you expect? 0? 1? any number? This could be, for example:
var profileIds = myfriends.Select(x => x.ProfileId);
...
new {profileIds}
...
AND profileID in #profileIds
or maybe:
new {profileId = myfriends.Single().ProfileId}
...
AND profileID = #profileId

RavenDB LINQ query against index fails

I get the following error when trying to run a specific query against RavenDB:
Can't extract value from expression of type: ArrayIndex
Here is the query that is generating the error:
people = from p in RavenSession.Query<DBObjects.Person, People_ByNameAndTrashedSortByFirstNameAndLastName>()
orderby p.FirstName, p.LastName
select p;
...
//building LINQ query
...
people = from p in people
where ((p.FirstName.StartsWith(SearchWords[0])) && (p.LastName.StartsWith(SearchWords[1])))
select p;
...
//later
foreach(DBObject.Person person in people) //triggers error listed above
{
}
I'm wondering if this is a limitation of RavenDB. I noticed that if I switch && with ||, then I get no error. Of course, I don't get the results I want either. I've also tried rewriting the query as:
people = from p in people
where p.FirstName.StartsWith(SearchWords[0])
where p.LastName.StartsWith(SearchWords[1])
select p;
I get the same error.
I've also tried using a dynamic index instead of a static index. I get the same error.
I suppose maybe RavenDB LINQ driver cannot cope with extracting value from array inside the query. Try to put already extracted values in the place of SearchWords[0] and SearchWords[1] instead:
var pref1 = SearchWords[0];
var pref2 = SearchWords[1];
... where ( p.FirstName.StartsWith(pref1) && p.LastName.StartsWith(pref2) )

Linq to CRM - Invalid operation exception

I'm using a LINQ to CRM from Advanced Developer Extension for MS CRM 4.0. It works fine with direct queries. But I've got a problem when query looks like this:
var connectionString = #"User ID=u; Password=p; Authentication Type=AD; Server=http://crm:5555/UO";
var connection = CrmConnection.Parse(connectionString);
var dataContext = new CrmDataContext(connection);
var data = from u in dataContext.Accounts
select new
{
Id = u.AccountID,
Name = u.AccountName,
};
var r = from n in data
where n.Name.StartsWith("test")
select new
{
Id = n.Id
};
r.Dump();
it throws an InvalidOperationException "Cannot determine the attribute name."
It's fine when a condition is directly in first query:
var data = from n in dataContext.Accounts
where n.AccountName.StartsWith("test")
select new
{
Id = n.AccountID,
Name = n.AccountName,
};
I cannot find any useful information about this kind of error. Is it a bug in Xrm Linq Provider?
Thanks in advance for any help.
Try eager loading the initial query with a ToList() so the latter query over your anonymous type is then evaluated locally. I get this is far from ideal if you have a lot of accounts but it'll prove the point. You essentially have a solution anyway in the last statement.
This is because the first query isn't executed at all until you call .Dump() at which point the entire expression including the second query is evaluated as one (deferred execution) by the provider which then looks for an attribute of Name.

Linq to NHibernate Distinct() "Expression type not supported" error

I've got the following code:
var data = (from v in this.GetSession().Query<WorkCellLoadGraphData>()
where v.WorkCellId == "13"
select
new WorkCellLoadGraphData
{
RowId = v.RowId,
WorkCellId = v.WorkCellId,
WorkCellName = v.WorkCellName,
WorkCellGroupId = v.WorkCellGroupId,
WorkCellGroupName = v.WorkCellGroupName
});
return data.Distinct();
If I don't call the Distinct() extension method, I have no issues whatsoever. However, if I do call the Distinct() method, I get the following error:
Expression type 10005 is not supported
by this SelectClauseVisitor.
After some searching I came across this:
https://nhibernate.jira.com/browse/NH-2380
But as you can see I'm not returning an anonymous type.
Has anyone else come across this issue? If so, how did you solve it?
David
Could this work? By using an anonymous type in the query, you would allow NHibernate to make the distinct query in the database. When using your own type, the comparison must be used with the class' Equals method.
var data = (from v in this.GetSession().Query<WorkCellLoadGraphData>()
where v.WorkCellId == "13"
select
new
{
v.RowId,
v.WorkCellId,
v.WorkCellName,
v.WorkCellGroupId,
v.WorkCellGroupName
})
.Distinct()
.Select (v =>
new WorkCellLoadGraphData{
RowId = v.RowId,
WorkCellId = v.WorkCellId,
WorkCellName = v.WorkCellName,
WorkCellGroupId = v.WorkCellGroupId,
WorkCellGroupName = v.WorkCellGroupName});

Resources