EF Core throws NullReferenceException while comparing strings with CompareOptions - postgresql

I have a Worker entity with string Name property, and just want to filter all Workers whose Name contains some specific string (from frontend text input).
When I do the filtering with:
_context.Workers.Where(w => w.Name.ToUpper().Contains(filter.ToUpper()).ToList()
it is working but it does not solves some specific diacritics in filter term.
When i try with:
var compareInfo = CultureInfo.InvariantCulture.CompareInfo;
_context.Workers.Where(w => compareInfo.IndexOf(w.Name, filter, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) > -1).ToList()
i get System.NullReferenceException: 'Object reference not set to an instance of an object.'
and console An exception occurred in the database while iterating the results of a query for context type 'Project.MyDbContext'.
I've also tried with
_context.Workers.Where(w => compareInfo.IndexOf((w.Name??""), filter, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase) > -1).ToList()
to perform a null check, but same.
Did anyone have same problem, or maybe idea what could be changed here so I could accompiish searching with diacritics?
Thx!

Related

Fix issue in CodeEffects editor return error in MVC

I have issue when filter data using filter editor, I'm using object(order) to get data
I get this error :
System.NotSupportedException: 'Cannot compare elements of type 'System.Collections.Generic.ICollection`1[[CodeEffects.Rule.Asp.Demo.Entities.Order, CodeEffects.Rule.Asp.Demo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Only primitive types, enumeration types and entity types are supported.'
enter image description here
The Entity Framework no longer, if it ever did, supports comparison of related tables with null. The CodeEffects probably needs to adjust their code to account for it.
As a workaround, set EvaluationParameters.PerformNullChecks = false as in:
EvaluationParameters evps = new EvaluationParameters
{
LINQProviderType = LinqProviderType.Entities,
PerformNullChecks = false
};
You pass those parameters in the Evaluator's constructor.
Note, this will disable all null-checks, which may or may not be a problem in your particular case.

operator does not exist: # timestamp without time zone

In a parameterized query issued from c# code to PostgreSQL 10.14 via dotConnect 7.7.832 .NET connector, I select either a parameter value or the local timestamp, if the parameter is NULL:
using (var cmd = new PgSqlCommand("select COALESCE(#eventTime, LOCALTIMESTAMP)", connection)
When executed, this statement throws the error in subject. If I comment out the corresponding parameter
cmd.Parameters.Add("#eventTime", PgSqlType.TimeStamp).Value = DateTime.Now;
and hardcode
using (var cmd = new PgSqlCommand("select COALESCE('11/6/2020 2:36:58 PM', LOCALTIMESTAMP)", connection)
or if I cast the parameter
using (var cmd = new PgSqlCommand("select COALESCE(cast(#eventTime as timestamp without time zone), LOCALTIMESTAMP)", connection)
then it works. Can anyone explain what # operator in the error is referring to and why the error?
In the case that doesn't work, your .Net connection library seems to be passing an SQL command containing a literal # to the database, rather than substituting it. The database assumes you are trying to use # as a user defined operator, as it doesn't know what else it could possibly be. But no such operator has been defined.
Why is it doing that? I have no idea. That is a question about your .Net connection library, not about PostgreSQL itself, so you might want to add tag.
The error message you get from the database should include the text of the query it received (as opposed to the text you think it was sent) and it is often useful to see that in situations like this. If that text is not present in the client's error message (some connection libraries do not faithfully pass this info along) you should be able to pull it directly from the PostgreSQL server's log file.

Crash with Lucene.NET when using Sort

I have a date field inserted in a Lucene database with the following code:
Document.Add(new NumericField("TimeStamp", Field.Store.YES, true).SetLongValue(Data.TimeStamp.ToBinary()));
And I have the following query:
var Sort = new Sort(new SortField("TimeStamp", SortField.LONG, true));
var ParsedQuery = ParseQuery(_Parser, SearchQuery);
var Filter = new QueryWrapperFilter(ParsedQuery);
var Hits = _Searcher.Search(ParsedQuery, Filter, Skip + Limit, Sort);
But it crashes when executing the search method with the following:
A first chance exception of type 'Lucene.Net.QueryParsers.QueryParser.LookaheadSuccess' occurred in Lucene.Net.dll
A first chance exception of type 'System.IO.IOException' occurred in Lucene.Net.dll
A first chance exception of type 'System.IO.IOException' occurred in Lucene.Net.dll
A first chance exception of type 'System.AccessViolationException' occurred in HDIndexing.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
If I replace the Sort variable with one of the constants, such as Sort.RELEVANCE then the search works properly.
The problem comes from my custom search.
Incidentally I noticed something else odd and I do not know if these is a connection: If I inspect my Lucene DB with the Luke tool, all my fields are reported to be strings:
http://i.stack.imgur.com/SnlSD.png
I do not know if this is a bug in Luke or something is wrong with how Lucene is set up on my end.
I tried to change the sort to a type 'string' to see what would happen, but it crashes the same way, so either way, the type of the field doesn't seem to have an impact.
Has anyone experienced that problem before?
It could be similar to someone else's post: lucene.net sort not working access violation

Grails Grom + mongoDb get during save OptimisticLockingException

I try in Grails service save an object to mongodb:
Cover saveCover = new Cover()
saveCover.id = url
saveCover.url = url
saveCover.name = name
saveCover.sku = sku
saveCover.price = price
saveCover.save()
Cover domain looks like this:
class Cover {
String id
String name
String url
String sku
String price
}
So I want to have custom id based on url, but during save process I get error:
Could not commit Datastore transaction; nested exception is
org.grails.datastore.mapping.core.OptimisticLockingException: The
instance was updated by another user while you were editing
But if I didn`t use setters and just pass all values in constructor, the exception is gone. Why?
As reported in the documentation here:
Note that if you manually assign an identifier, then you will need to use the insert method instead of the save method, otherwise GORM can't work out whether you are trying to achieve an insert or an update
so you need to use insert method instead of save when id generator is assigned
cover.insert(failOnError: true)
if you do not define the mapping like this:
static mapping = {
id generator: 'assigned'
}
and will use insert method you'll get an auto-generated objectId:
"_id" : "5496e904e4b03b155725ebdb"
This exception occurs when you assign an id to a new model and try to save it because GORM thinks it should be doing an update.
Why this exception occurs
When I ran into this issue I was using 1.3.0 of the grails-mongo plugin. That uses 1.1.9 of the grails datastore core code. I noticed that the exception gets generated on line 847(ish) of NativeEntryEntityPersister. This code updates an existing domain object in the db.
Above that on line 790 is where isUpdate is created which is used to see if it's an update or not. isInsert is false as it is only true when an insert is forced and readObjectIdentifier will return the id that has been assigned to the object so isUpdate will end up evaluating as true.
Fixing the exception
Thanks to && !isInsert on line 791 if you force an insert the insert code will get called and sure enough the exception will go away. However when I did this the assigned id wasn't saved and instead a generated object id was used. I saw that the fix for this was on line 803 where it checks to see if the generator is set to "assigned".
To fix that you can add the following mapping.
class Cover {
String id
String name
String url
String sku
String price
static mapping = {
id generator: 'assigned'
}
}
A side effect of this is that you will always need to assign an id for new Cover domain objects.

Linq To Entities: "Sequence contains no elements" with Count()

In our appliction we have a piece of code with some Linq-queries (EF) that sometimes throws an exception.
This has only happened to the end user, and we are not able to reproduce it so far.
From the logfile we got the following stacktrace for the exception:
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.Single[TSource](IEnumerable1 source)
at System.Data.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__3[TResult](IEnumerable1 sequence)
at System.Data.Objects.ELinq.ObjectQueryProvider.ExecuteSingle[TResult](IEnumerable1 query, Expression queryRoot)
at System.Data.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable1 source)
at MT3.uctXGrid.LoadLayout(String strUniqueID, Boolean rethrowException, List`1 visibleColumns)
In the method LoadLayout there are only 2 instances of Count(), and they are just operating on standard IQueryables which interrogate an entity type based on one integer field and select all fields (no aggregations or anything).
ex:
from p in cxt.genData where datId = ID
In the stacktrace, it seems like internally .Single() is being used which could throw an exception if there are no records.
But why is it using single if we are just calling .Count() ?
How can a query like
(from p in cxt.genData where datId = ID).Count()
throw a "sequence contains no elements" exception?
We have had other strange problems with queries as well, I'm starting to wonder if there are any issues with our version of EF maybe.
We are still on 4.0 at the moment. (Standard version which came with VS2010).
Has anyone got an idea what could be going on here?
Update:
Here are the Linq-to-Entities queries we actually use
Dim qryLastLayout = From t In oContext.genGridLayouts Where t.layID = intCurrentLayoutID
If Not IsNothing(qryLastLayout) AndAlso qryLastLayout.Count <> 0 Then
Dim qryPrintSettings = From p In oContext.genPrintSettings Where p.prtDefault = True
If Not IsNothing(qryPrintSettings) AndAlso qryPrintSettings.Count <> 0 Then
Have you tried using the .Any() method?
if(cxt.genData.Any(x => x.datId == ID))
{
// do something here
}
One thing to be aware of wrt Linq to Entities is that the semantics of Count() are not those of .NET but those of the underlying datasource (somewhat undermining the whole language-integration aspect, but oh well...). I don't think this can cause issues like yours, but you never know.
MSDN link with more details: http://msdn.microsoft.com/en-us/library/vstudio/bb738551.aspx#sectionSection5