Using contains on an integer in LINQ to SQL - vb.net

I'm trying the following query:
Return _context.companies _
.Where(Function(c) c.id.StartsWith(filterCompanyId)) _
.ToList()
but because id is an integer, it doesn't work. I found this answer which suggests I can use
c.id.ToString().StartsWith ...
but that gives me the following error:
LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
When trying to use
.Where(Function(c) SqlFunctions.StringConvert(CDbl(c.id)).StartsWith("1"))
it doesn't work.
Any tips?

The relevant part is hidden in the error message:
'SqlFunctions' is not declared. It may be inaccessible due to its protection level
SqlFunctions is in the System.Data.Objects.SqlClient namespace (you can discover this by going to the "SqlFunctions Class" MSDN page and then checking the "Namespace:" entry). Thus, you need to import that namespace at the top of your code file:
Imports System.Data.Objects.SqlClient

Per #Heinzi's comment, StringConvert is not supported by the MySQL-EF-Provider. I ended up going with a query string:
Dim isExpiredInt As Integer = If(isExpired, 1, 0)
Dim query As String = "Select * FROM company WHERE (expired = 0 OR expired = {0}) AND name like {1} AND id like {2}"
Dim companies = _context.ExecuteStoreQuery(Of company)(
query,
"companies",
System.Data.Objects.MergeOption.AppendOnly,
isExpiredInt, "%" & filterCompanyName & "%", filterCompanyId & "%"
).ToList()
Return companies
Note the System.Data.Objects.MergeOption.AppendOnly is something I added so the objects from this query would be attached to my context (i.e. calling SaveChanges on this context would write to the database).
Hope that helps!

Related

LINQ retrieving a record based on date

I am trying to learn a bit about ling. in the code below, I'm trying to retrieve records that have an activeuntil date which after the current date.
Dim context As DynamicsCRMEntities = New DynamicsCRMEntities()
Dim CustomerNoticeQuery = From NewsArticles In context.BusinessUnitNewsArticles Where NewsArticles.NewsArticle Like "customer" Select NewsArticles.ArticleTitle, NewsArticles.NewsArticle, NewsArticles.ActiveUntil
For Each result In CustomerNoticeQuery
If Date.Now.Date >= result.ActiveUntil Then
CustomerNotice.Text = result.NewsArticle.ToString
End If
Next
I keep running into this error but cannot get my head around it
System.NotSupportedException: 'LINQ to Entities does not recognize the method 'Boolean LikeString(System.String, System.String, Microsoft.VisualBasic.CompareMethod)' method, and this method cannot be translated into a store expression.'
The Like operator you are using there is VB-specific and, as the error message says, is not supported by EF. You need to use standard .NET functionality that the LINQ to Entities provider understands. If you want to do a partial match on Strings, that means using String.Contains:
Dim CustomerNoticeQuery = From NewsArticles In context.BusinessUnitNewsArticles
Where NewsArticles.NewsArticle.Contains("customer")
Select NewsArticles.ArticleTitle, NewsArticles.NewsArticle, NewsArticles.ActiveUntil
You really ought to break your LINQ queries over multiple lines like that too, for the sake of readability.
Note that that addresses your actual issue, which has nothing to do with dates, so the date part to the question was completely irrelevant. That said, why would you do a query with a Where clause and then use a loop to filter the results of that query? Why would you not include the additional filter in the Where clause? I'd also consider using a better subject variable name in the query:
Dim today = Date.Today
Dim CustomerNoticeQuery = From article In context.BusinessUnitNewsArticles
Where article.NewsArticle.Contains("customer")
And article.ActiveUntil < today
Select article.ArticleTitle, article.NewsArticle, article.ActiveUntil

The ""sort"" value has to be formed as this example: ""field_ASC""

I'm developing an integration between a ERP and a Prestashop store, I'm now trying to use a product filter to check if a product already exists, so i can either add a new product or update an existing one.
When I try to get the filter result i got a XML response with the following error message
<![CDATA[The ""sort"" value has to be formed as this example: ""field_ASC"" or '[field_1_DESC,field_2_ASC,field_3_ASC,...]' (""field"" has to be an available field)]]>
I didn't understand what that really means, I have searched around a while and coudn't find any specific problem like this and all the examples I've found are the same.
Here is my code, it is in VB and I'm using Bukimedia Prestasharp
Dim oProdFac = New ProductFactory(oParameters.UrlAPI, oParameters.TokenAPI, oParameters.KeyAPI)
Dim objFiltro = New Dictionary(Of String, String)
Dim listFilterProducts As New List(Of Bukimedia.PrestaSharp.Entities.product)
objFiltro.Add("reference", "My_Product_Id")
listFilterProducts = oProdFac.GetByFilter(objFiltro, "null", "null")
What am I doing wrong?
Allright, the answer is SO SIMPLE that i felt ashamed.
I was sending incorrect parameters in the GetByFilter function.
I've changed this
listFilterProducts = oProdFac.GetByFilter(objFiltro, "null", "null")
to this
listFilterProducts = oProdFac.GetByFilter(objFiltro, "reference_ASC", "null")
Just like the xml message said. It solved the problem.

How do I use ICalculator in ArcEngine?

I'm trying to calculate value for field from the attribute table of a shapefile using ArcEngine, looking up in EDN & ArcGIS help and I wrote code as below:
ICalculator pCalculator = new Calculator();
pCalculator.Field = pField.Name;
string ex = "!POP06!-!POP02!";
pCalculator.Expression = ex;
pCalculator.Calculate();
pField is the target field I want to update the value, POP06 & POP02 are two fields I use to calculate, using ! for python.
When I run the program VS2010 said "Error HRESULT E_FAIL has been returned from a call to a COM component". I could tell that ICalcultor haven't set any dependence on attribute table, but I don't know how to do. Also, are there any other problems in my code?

Nest ElasticSearch cannot convert Lambda expression

The following VB code is intended to add an alias index to a nest elastic search but the final line receives an error -
"lambda expression cannot be converted to NEST.IAliasRequest because Nest.IAliasRequest is not a delegate type"
Dim client = ConnectToSearch()
Dim Person = New Person With {.Id= Id, .Description = Description, .Tags = Tags}
client.Alias(Sub(a) a.Add(Function(add) add.Index("Person").Alias("Account1")))
client.[Alias](Function(descriptor) descriptor.Add(Function(a) a.Index("Person").[Alias]("Account1")))
UPDATE
Maybe this one will help you create alias with filter.
client.[Alias](Function([alias]) [alias].Add(Function(a) a.Index(indexName).[Alias]("alias").Filter(Of Person)(Function(f) f.Term("relationships.staffID", staffID))))
Hope this helps.

Nhibernate.Search, Lucene, and the Criteria API: types mismatch

Update
I've been looking around the NHibernate.Search.Tests project to find out how the Criteria API is used (i find it immensely useful to look around the test code to have working examples) and i noticed that the way to use the Fulltext search is radically different. Here are two tests, one with the criteria API, one with the classic query schema:
[Test]
public void ResultSize()
{
IFullTextSession s = Search.CreateFullTextSession(OpenSession());
ITransaction tx = s.BeginTransaction();
// snipped the objects creation
QueryParser parser = new QueryParser("title", new StopAnalyzer());
Lucene.Net.Search.Query query = parser.Parse("Summary:noword");
IFullTextQuery hibQuery = s.CreateFullTextQuery(query, typeof(Clock), typeof(Book));
Assert.AreEqual(0, hibQuery.ResultSize);
// snipped the end of the test
}
[Test]
public void UsingCriteriaApi()
{
IFullTextSession s = Search.CreateFullTextSession(OpenSession());
ITransaction tx = s.BeginTransaction();
// snipped creation
IList list = s.CreateCriteria(typeof(Clock))
.Add(SearchRestrictions.Query("Brand:seiko"))
.List();
Assert.AreEqual(1, list.Count, "should get result back from query");
// snipped deletion
}
The second solution works under vb.net, at the cost of the useful Lucene query (which embarks it's own total of the corresponding rows) and at the cost of the Lucene ordering (or i couldn't find it)
Hello everyone,
yet again, i'm stumped on the path, but this time, i suspect something a bit more sinister than my usual erratic errors (cue ominous music)
I'm trying to combine FullText search using Lucene.net with paging and the Criteria API.
So far paging and the Fulltext search have been working flawlessly. Recently though, we had to use the criteria API to add specific filters to the query. So what i did was the following:
Create the Nhibernate.Search query object using the following
Private Function GetQuery(ByVal QueryString As String, ByVal Orders() As String) As IFullTextQuery
Dim ifts As IFullTextSession = Search.CreateFullTextSession(UnitOfWork.CurrentSession)
Dim analyzer As New SimpleAnalyzer
Dim parser As New MultiFieldQueryParser(SearchPropertyNames, analyzer)
Dim queryObj As Lucene.Net.Search.Query = parser.Parse(QueryString)
Dim nhsQuery As IFullTextQuery = ifts.CreateFullTextQuery(queryObj, New System.Type() {GetType(T)})
For i As Integer = 0 To Orders.Count - 1
Orders(i) = Orders(i) & "FS"
Next
nhsQuery.SetSort(New Sort(Orders))
then add my Criteria to the query:
Dim crit As ICriteria = ifts.CreateCriteria(GetType(T))
Dim criterion As ICriterion
If criteria IsNot Nothing Then
For Each criterion In criteria
If (Not criterion Is Nothing) Then
crit.Add(criterion)
End If
Next
End If
nhsQuery.SetCriteriaQuery(crit)
but when i list the resulting query, i receive the following exception
Criteria query entity should match query entity
A quick glance in the FullTextQueryImpl source file (method GetLoader) shows that there is a comparison between the type name given to the NHibernate.Search query object and the EntityOrClassName property for the Criteria object. That's where my problems appear because the FullTextQueryImpl uses the Name, and the Criteria uses the Fullname. Here's a constructor code for the CriteriaImpl class
Public Sub New(ByVal persistentClass As Type, ByVal session As ISessionImplementor)
Me.New(persistentClass.FullName, CriteriaSpecification.RootAlias, session)
Me.persistentClass = persistentClass
End Sub
and here's the comparison:
Dim entityOrClassName As String = DirectCast(Me.criteria, CriteriaImpl).EntityOrClassName
If ((Me.classes.GetLength(0) = 1) AndAlso (Me.classes(0).Name <> entityOrClassName)) Then
Throw New SearchException("Criteria query entity should match query entity")
End If
As a result, the comparison fails and the exception is thrown. I tried playing around with the aliases to no avail since the comparison is not using the aliases.
Am i missing something huge in my mix of the Fulltext search and the Criteria API, or is it something else? Does it work as expected in C#, because i'm having a weird feeling that it could be vb.net related?
Thank you for reading,
Samy
Looks like this has been resolved with revision 1611 of NHibernate.Search :
Revision: 1611
Message: Fixed a bug where a full class name was being compared against a partial one. This was causing LuceneQueryTest.UsingCriteriaApi to fail.
Modified : /trunk/src/NHibernate.Search/src/NHibernate.Search/Query/FullTextQueryImpl.cs
svn : https://nhcontrib.svn.sourceforge.net/svnroot/nhcontrib/trunk/src/NHibernate.Search/