Getting an error while filtering an entity results using contains (like operator) - entity

Could you please help me to filer a results using contains (like operator) which as following...
Public Function GetFromCacheByParentID(ParentID As String, Criteria As String) As List(Of tbl_equip_master)
Dim RelatedData = _RelatedData.GetFromCache
Dim EquipMaster = Me.GetFromCache
return (From e In EquipMaster, r In RelatedData Where r.linked_for = "EQP" And e.global_id = r.child_id And r.parent_id = ParentID And (e.tag_no.Contains(Criteria) Or e.object_name.Contains(Criteria) Or e.object_type.Contains(Criteria)) Select e)
End Function
My intention is calling 2 results from cashed data and try to join and filter using contains
But i am getting an error on ".contains".

I trace out the issue, reason is "e.object_name value is Nothing" - data from sql server. so code "e.object_name.Contains(Criteria)" throws an error...
And another question is raising how we can avoid such situation...any idea please...

All issue has solved by using following code by trapping "null" value
Public Function GetFromCacheByParentID(ParentID As String, Criteria As String) As List(Of tbl_equip_master)
Dim _RelatedData As IRelatedDataV2 = New RelatedDataV2
Dim RelatedData = _RelatedData.GetFromCache
Dim EquipMaster = Me.GetFromCache
Return (From e In EquipMaster, r In RelatedData Where r.linked_for = "EQP" And e.global_id = r.child_id And r.parent_id = ParentID And (e.tag_no.Contains(Criteria) _
Or (Not IsNothing(e.object_name) AndAlso e.object_name.Contains(Criteria))) Select e).ToList
End Function

Related

Unable to cast object error when attempting to return key/value pairs by querying a datacontext

I am attempting to get data from a datacontext. Normally, I've had no problems doing it, but I'm having trouble trying to return a list of key/value pairs.
Basically I'm attempting to grab all unique names from a table as the key column and the number of times they appear in the table as the value column.
My data would look like this:
apple 5
banana 1
dragonfruit 3
.
.
.
The full error message is:
Unable to cast object of type 'System.Data.Linq.DataQuery1[VB$AnonymousType_32[System.String,System.Int32]]' to type 'System.Collections.Generic.List`1
The code I'm using is this:
Dim indicators As List(Of Object)
Public Sub GetIndicatorData()
Using context = new A_DataContext
indicators = (From p In chartdata Group p By __groupByKey1__ = p.INDK8R Into g = Group
Select New With {.name = __groupByKey1__, .count = g.Count()}).AsEnumerable()
indDataSource = indicators
End Sub
but I've also tried to:
Return indicators as a list
Return indicators as an enumerable.
Use a class to encapsulate your anonymous type
Public Class NameAndCount
Public ReadOnly Property Name As String
Public ReadOnly Property Count as Integer
Public Sub New(name As String, count As Integer)
Me.Name = name
Me.Count = count
End Sub
End Class
' ...
Private indicators As IEnumerable(Of NameAndCount)
Public Sub GetIndicatorData()
Using context = new A_DataContext
indicators = From p In chartdata Group p By __groupByKey1__ = p.INDK8R Into g = Group
Select New NameAndCount(__groupByKey1__, g.Count())
indDataSource = indicators.ToList()
End Using
End Sub
Figured it out. I changed the declaration of indicators to simply be an object then removed the .enumerable (or .toList) from the query result.
Thank you for the consideration and time.

error unable to cast object of type System.Collections.Generic.List to type System.Linq.IQueryable

My code is :
' GET: odata/Event_Game_Schedule
<EnableQuery>
Function GetEvent_Game_Schedule() As IQueryable(Of Event_Game_Schedule)
Dim schedule As New List(Of Event_Game_Schedule)
schedule = db.Event_Game_Schedule.ToList()
For Each x As Event_Game_Schedule In schedule
x.hometeamid = (From t In db.Teams Where t.id = x.hometeamid Select t.name).FirstOrDefault
x.visitorteamid = (From t In db.Teams Where t.id = x.visitorteamid Select t.name).FirstOrDefault
Next
Return schedule.AsQueryable.ToList()
End Function
what am I doing wrong .. this is a controller and I want to return the names of the teams instead of the teamid in the API.
thanks
I found the answer I needed only to add the ASQueryable part .. not the .ToList()
this is visual Basic for a vb.net project

VB net & Mongo: Using where clause with LINQ causes error "Unsupported where clause: (Boolean)Operators.CompareObjectLess"

I have a collection in MongoDB and I'm using MongoDB Driver in VB net. I want to update several documents depending on a condition.
For this, I want to use LINQ, but the select causes an error and I don't know how to fix it.
Here's the code:
Dim update_for As UpdateBuilder
Dim query_for As IMongoQuery
Dim coll_for = db.GetCollection(Of MyClass)("collection_1")
Dim queryMun = (From a In coll_for _
Where (a.field_1 < 10000) _
Select a)
For Each emp In queryMun
query_for = Query.EQ("_id", emp.Id)
update_for = Update.Set("field_1", BsonValue.Create("0" + emp.field_1))
coll.Update(query_for, update_for, opts)
Next
When it executes de For Each sentence, it raises the exception: Unsupported where clause: (Boolean)Operators.CompareObjectLess(a.field_1, 10000, true).
What am I doing wrong?
Thank you very much for your help.
I think the error is clear:
You can't use a Less Than "<" operator in you WHERE clause because it's unsupported.
I have found a way to do this update based on the value of the attribute itself. What I want to do is add a "0" at the beginning of the attribute value, for example, if field_1=4567, after the update field_1='04567'.
Here's the code:
Dim update_for As UpdateBuilder
Dim query_for As IMongoQuery
Dim opts = New MongoUpdateOptions
opts.Flags = UpdateFlags.Multi
Dim coll_for = db.GetCollection(Of MyLINQClass)("collection_1")
Dim queryMun2 As New QueryDocument
Dim query_1 = Query.LT("field_1", MongoDB.Bson.BsonValue.Create(10000))
queryMun2.AddRange(query_1.ToBsonDocument)
Dim queryMun = coll_for.Find(queryMun2)
For Each emp In queryMun
query_for = Query.EQ("_id", emp.Id)
update_for = Update.Set("field_1", BsonValue.Create("0" + emp.FField_1.ToString))
coll.Update(query_for, update_for, opts)
Next
And here is the definition of MyLINQClass:
Public Class MyLINQClass
<BsonElementAttribute("_id")> _
Public Property Id() As ObjectId
<BsonElementAttribute("field_1")> _
Public Property FField_1() As Object
End Class

Searching objects in a list

I have a list of objects, and I want to search it to see if myobject.articleID matches a given articleID. From what I've gather using .Find(Of T) is the best way to go about this, however I am having some difficulty implementing it. Here's some code I have so far:
<WebMethod()> _
Public Function SetTagOnFavorite(ByVal articleID As Integer, ByVal tagtext As String, ByVal mobileGUID As String) As AddTagResult
Dim result As New AddTagResult
Dim userID As Long = GetUserIDByMobileGUID(mobileGUID)
If userID > 0 Then
Dim pageNum As Integer = 1
Dim pageLen As Integer = 500 'arbitrarily large number
Dim savedArticleList As New List(Of SimpleArticle)
savedArticleList = GetSavedArticles(mobileGUID, pageNum, pageLen)
If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID)
Dim lq As New lqDFDataContext
Dim var = lq.web_AddTagToArticle(userID, articleID, tagtext).ToList()
If var.Any() Then
Dim vRes = var.First()
result.articletagID = vRes.articletagID
result.newarticletag = vRes.newarticletag
result.newusertag = vRes.newusertag
result.usertagID = vRes.usertagID
result.resultinfo = "Success."
End If
End If
Else
result.resultinfo = STR_NoUserIDMostLikelyTheSessionTimedOut
End If
Return result
End Function
The error I get is, "value of type SimpleArticle cannot be converted to Boolean".
Because Find(Of returns the found object, you need to change this line:
If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID)
to
If savedArticleList.Find(Function( m As SimpleArticle) m.articleID = articleID) IsNot Nothing
or if you need the found item, store the result of Find in a local variable.
You could optimize #competent_tech's answer further as:
If savedArticleList.Any(Function(m) m.articleID = articleID))

VB.Net Linq InvalidCastException for Group By

I have a Linq Group By query that works. Here's the query:
Dim query = From fb As Feedback In lst Where fb.Seller.login_name.ToLower = UserName.ToLower
Order By fb.transaction_id Descending, fb.creation Descending _
Group fb By fb.transaction_id _
Into Group
I don't like working with anonymous types so I'm trying to delare the result and am hitting an InvalidCastException.
Here's the type information:
Debug.Print(query.GetType.ToString)
Returns:
System.Linq.GroupedEnumerable`4[Feedback,System.Nullable`1[System.Int32],Feedback,VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]
and the inner type:
Debug.Print(item.GetType.ToString)
Returns:
VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]
So, armed with this information, here's the declaration used:
Dim query As IEnumerable(Of IGrouping(Of Int32?, IEnumerable(Of Feedback)))
Here's the error returned:
Unable to cast object of type 'System.Linq.GroupedEnumerable`4[Feedback,System.Nullable`1[System.Int32],Feedback,VB$AnonymousType_0`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]' to type 'System.Collections.Generic.IEnumerable`1[System.Linq.IGrouping`2[System.Nullable`1[System.Int32],System.Collections.Generic.IEnumerable`1[Feedback]]]'.
The Ugly solution is to define an object and step through the results as follows:
Class FeedbackDataItem
Sub New(ByVal transaction_id As Integer)
_transaction_id = transaction_id
_feedbacks = New Feedbacks(Of Feedback)
End Sub
Private _transaction_id As Integer
Public Property transaction_id() As Integer
Get
Return _transaction_id
End Get
Set(ByVal value As Integer)
_transaction_id = value
End Set
End Property
Private _feedbacks As Feedbacks(Of Feedback)
Public Property Feedbacks() As Feedbacks(Of Feedback)
Get
Return _feedbacks
End Get
Set(ByVal value As Feedbacks(Of Feedback))
_feedbacks = value
End Set
End Property
End Class
And to load up the collection:
Dim FeedbackData As New List(Of FeedbackDataItem)
For Each item In query
Dim fbi As New FeedbackDataItem(item.transaction_id)
fbi.Feedbacks.AddRange(item.Group)
FeedbackData.Add(fbi)
Next
I'm stumped as to the reason why I'm getting this error. It would be nicer to just define the results and retrun them rather that man-handle the data. Am I missing something?
The result of your query is an IEnumerable(Of anonymous type). If you don't want it to be anonymous, you need to strongly type it.
One way is to use the extension method syntax for the group by:
Dim feedbacks As IEnumerable(Of Feedback) =
From fb As Feedback In lst Where fb.Seller.login_name.ToLower = username.ToLower
Order By fb.transaction_id Descending, fb.creation Descending
Dim grouped As IEnumerable(Of IGrouping(Of Integer?, Feedback)) =
feedbacks.GroupBy(Function(fb) fb.transaction_id)
Put a select at the end of the statement to get it into whatever type you want.
Dim query = From fb As Feedback In lst _
Where fb.Seller.login_name.ToLower = UserName.ToLower
Order By fb.transaction_id Descending, fb.creation Descending _
Group gr By fb.transaction_id
Into Group
Select new FeedbackDataItem with {
.transaction_id = gr.transaction_id, _
.FeedBacks = ...
}