I have a pretty straight forward query that is producing this error at runtime: Only arguments that can be evaluated on the client are supported for the String.Contains method.
The query is supposed to find only the categories that have transfers assigned to them. The transfers can be listed in several categories so there is no table relationship. The Categoryidhash contains data like "7~34~25~42~47". I just realized while writing this that searching for '7' will return multiple results, "7" & '47' Etc. Thats ok i'll just change id's to all double digits. meanwhile...
How can I fix this?
Private Function GetCategoryList() As List(Of Category)
Dim lst As List(Of Category) = New List(Of Category)
Using db As New IPCDataDataContext
lst = (From c In db.Categories
From t In db.Transfers
Where t.CategoryIDhash.Contains(c.ID.ToString)
Select c).ToList()
Return lst
End Using
End Function
The exception means that Contains only accepts arguments that can be converted to fixed variable in SQL. So something like Where t.CategoryIDhash.Contains(someVariable.ToString) would be possible, because someVariable.ToString can be evaluated client-side.
I don't really understand this restriction, because in SQL it is perfectly possible to use a LIKE clause with a string that is built in the SQL statement itself. This is demonstrated by the statement that fixes your problem:
lst = (From c In db.Categories
From t In db.Transfers
Where SqlMethods.Like(t.CategoryIDhash, "%" + c.ID.ToString "%")
Select c).ToList()
This generates (and executes) SQL like
...
WHERE [t1].[CategoryIDhash] LIKE (#p0 + (CONVERT(NVarChar,[t0].[ID]))) + #p1
(where #p0 and #p1 are the % characters.
Although you could do this, I wonder if you're on the right track by using this CategoryIDhash. I think you should convert it to a FK relationship (if it's in your hands to modify the database).
Related
I am looking to do something like:
select * from MyValues
where CONTAINS(MyValues.Value, ' #p0 OR #p1 OR #p2 or #p3 ')
I issue the query through EF's SqlQuery() method like:
query = context.Database.SqlQuery<MyResult>(#"select * from MyValues
where CONTAINS(MyValues.Value, '#p0 OR #p1 OR #p2 OR #p3')",
new SqlParameter("#p0", "Cat"),
new SqlParameter("#p1", "Green"),
new SqlParameter("#p2", "Red"),
new SqlParameter("#p3", "Dog"));
The command goes through fine, no exceptions, but I do not receive any results. When I manually use the strings in place of the parameters, I get the expected results. I've tried various forms and combinations of quotation marks but to no avail.
Are SQL Parameters allowed within a CONTAINS expression?
Thanks!
Because the CONTAINS function uses a single string, I don't believe that you can use parameters as you have them. You can try building up the full string and passing that in as a single parameter however. As long as the string that you build is then passed in as a parameter I believe that you'll avoid any issues with possible SQL injection.
May be you can try this.
query = context.Database.SqlQuery<MyResult>(#"select * from MyValues)
Once you get your list.filter it using below query.
First put all your parameters in a string array.
string[] paramValues= [p1,p2,p3,p4]
var results=query.where(r=> paramValues.Contains(r.Value));
Note:If your resultset is huge.it's not a good idea to return all results to front end and do filter.in most cases you have other conditions to filter.
I'm trying to understand what this LINQ statement is actually doing. I have no experience in LINQ, so I'm trying to get somewhat of a "plain english" translation.
MyDataTable contains the following data:
OrderByValues, Contract, PayType, PayAmount
Dim groupIDs = From r In myds.MyDataTable Select OBV = r.Item("OrderByValues"), PT = r.Item("PayType"), Contract = r("Contract") Distinct
For Each r in groupIDS
a = r.OBV
b = r.PT
c = r.Contract
Next
I'm not sure if there is enough info here to help you out or not. I'd appreciate any help.
Thanks.
The first line creates an query that will hold a collection of anonymous types. The query is not executed yet because of LINQ's deferred execution. This can be broken down into pieces:
From r In myds.MyDataTable defines r as an individual element of the IEnumerable (usually array or List)) myds.MyDataTable
Select OBV = r.Item("OrderByValues"), ... Distinct creates an anonymous type with properties called OBV, PT, Contract and assigns those properties values from the element r.
The foreach loop actually executes the query and creates the IEnumerable to iterate over. Then within this loop, it repeatedly sets a,b,c to the properties of the anonymous type defined in the query. This does seem a bit strange, since the variables a,b,c will only remember the last value set to them.
More reading on LINQ.
It selects all "OrderByValues", "PayType", and "Contract" columns from your datatable, ignoring duplicate rows.
It then iterates over the resultset, and assigns the 3 values to the variables "a", "b", and "c" respectively.
Using Entity Framework, I'm trying to join two tables like this.
...
join f in ent.FTypes on Int32.Parse(c.CourseID[0].ToString()) equals f.FTypeID
...
The first character of the string CourseID is a digit, and FTypeID is an int.
This doesn't seem to work though. The exception message I get is:
LINQ to Entities does not recognize the method 'Int32 Parse(System.String)' method, and this method cannot be translated into a store expression."} System.Exception {System.NotSupportedException}
What I want to replicate is the SQL string equivalent (which works fine):
join FType f on SUBSTRING(c.CourseID, 1, 1) = f.FTypeID
Does anyone have the solution to have to do this in LINQ to Entities?
This is a rather nasty join, but I did some testing in Entity Framework with similar data and arrived at something you can test on yours.
It uses string.Substring to grab the first character from your string operand, and then uses a combination of the EF-only method SqlFunctions.StringConvert (these methods are found in System.Data.Objects.SqlClient) with a cast to double1 and finally a string.Trim2 for your integer operand.
I have tested this and confirmed that all functions are supported at least in EF 4. Several other methods proposed or featured in the question do not work, because Entity Framework does not know how to tranlsate them to the appropriate SQL equivalent.
join f in ent.FTypes
on c.CourseID.Substring(0, 1)
equals SqlFunctions.StringConvert((double)f.FTypeID).Trim()
It produces a SQL join that looks like the following:
INNER JOIN [dbo].[FTypes] AS [Extent2]
ON ((SUBSTRING([Extent1].[CourseID], 0 + 1, 1)) = (LTRIM(RTRIM(STR( CAST( [Extent2].[FTypeID] AS float))))))
OR ((SUBSTRING([Extent1].[CourseID], 0 + 1, 1) IS NULL) AND (LTRIM(RTRIM(STR( CAST( [Extent2].[FTypeID] AS float)))) IS NULL))
So based on that, you might want to do some additional filtering as necessary.
Give it a shot and see if that helps solve the problem.
1 The cast to double is necessary because SqlFunctions.StringConvert does not have an overload for integer and there is no other single best match, so I force one.
2 The resultant string needs to be trimmed because the string conversion generates some excess padding.
I'm not sure this worked 8 years ago, but modern EF6 implementation allows you to add anonymous types, so you can add the conversion to your initial select statements, and then you can just compare that new properties directly in the join.
from c in ent.Courses
select new { typeId = c.CourseId.Substring(0, 1), c }
join f in ent.FTypes.Select(t => new { stringId =
t.FTypeId.ToString(), t }
on c.typeId equals f.stringId into ...
NOTE: The join-statement does not appear to support ToString() but the select-statements do.
You could also move the CouresId.Substring into the join statement, but that may run less efficiently there.
Results in SQL like this:
INNER JOIN [ent].[FTypes] AS [Extent2] ON
(LTRIM(RTRIM(SUBSTRING([Extent1].[nvarchar(max)], 3 + 1, 1)))) =
CAST([Extent2].[Id] AS nvarchar(max))
I have a List(Of Hardware) - the List is called HWModels
Class Hardware has the following Properties:
ModelName
Status
CPUStatus
MemoryStatus
DiskStatus
The List is populated by reading a CSV file, once it's populated, I want to return the distinct records based on the ModelName
I've attempted by doing it as follows:
(From a In HWModels Select a.ModelName).Distinct
But this isn't right because I end up with a list of only the ModelName's and nothing else.
How do I get the Distinct function to return all of the other class members within the list?
LINQ to Objects doesn't provide anything to do "distinct by a projection" neatly. You could group by the name and then take the first element in each group, but that's pretty ugly.
My MoreLINQ provides a DistinctBy method though - in C# you'd use:
var distinct = HWModels.DistinctBy(x => x.ModelName).ToList();
Presumably the VB would be something like
Dim distinct = HWModels.DistinctBy(Function(x) x.ModelName).ToList
Apologies for any syntax errors though :(
This will group your objects by the preferred property and then will select the first of each one, removing duplicates.
Dim newlist = HWModels.GroupBy(Function(x) x.ModelName).Select(Function(x) x.First).ToList
This is giving me a headache. I have this link query here that grabs an ID
Dim mclassID = From x In db.SchoolClasses Where x.VisitDateID = _visitdateID Select x.ClassID
And then later on I have this linq query
ViewData("Staff") = From t In db.Staffs Where t.ClassID = mclassID Select t
Any help would be much appreciated. I've tried quite a few things but to no avail. I've attempted casting, converting, Is operand, etc.
The problem is that myClassID is an anonymous IQueryable. You need to force it into another type (List is my favorite), and then pull it out of that type. So if you were to select it into a List(Of Integer) you could then extract the First() one since it would be the only. You could try something like this:
Dim myClassIDList As List(Of Integer) = New List(Of Integer)( _
From x In db.SchoolClasses Where x.VisitDateID = _visitdateID Select x.ClassID)
Dim myClassID as Integer = myClassIDList.First()
Just a guess, but would it help to wrap the right-side of the equation in parenthesis? I.e.:
ViewData("Staff") = (From t In db.Staffs Where t.ClassID = mclassID Select t)
Using the Select operator, you can have multiple results returned. If you are only expecting one result (i.e. you are selecting by a primary key), then you can use Single or SingleOrDefault (depending on whether there is guaranteed to be a result) to get just that one.
Dim mclassID = (From x In db.SchoolClasses _
Where x.VisitDateID = _visitdateID _
Select x.ClassID).SingleOrDefault()
You should change this
Dim mclassID = From x In db.SchoolClasses Where x.VisitDateID = _visitdateID Select x.ClassID
to select a single instance or the first instance, otherwise it does as its reporting, returning an IEnumerable, which causes your error later.
Or you could change your second statement to something like
ViewData("Staff") = From t In db.Staffs Where mclassID.Contains(t.ClassID) Select t
taking advantage of the mclassID as an IEnumerable of int.
You can see the errors in Output if you set appropriate options: -
Navigate VS2010 menus to Tools/Options/Projects and solutions/Build and Run/
Set MSBuild Project build output verbosity to "Detailed"
I had a similar error that wasn't showing in the Error list, but with this options setting I saw: -
error BC30452: Operator '=' is not defined for types 'System.Nullable(Of Integer)' and 'Integer'.
from this statement: -
If tqGDBChart.UserIsGroupAdmin(Userid, Groupid) = 0 Then 'User is not a group admin for this group
Easily fixed it with an intermediate variable.
Dim GroupAdminCount As Integer = tqGDBChart.UserIsGroupAdmin(Userid, Groupid)
If GroupAdminCount = 0 Then 'User is not a group admin for this group
have you tried:
ViewData("Staff") = From t In db.Staffs Where t.ClassID.equals(mclassID) Select t