Executing the following NHibernate.Linq statement raises a "could not instantiate: Reservation001.Services.ReservationDto" NHibernate.QueryException containing an inner InvalidCast exception ("Object must implement IConvertible."):
var inOneStep = (from r in session.Linq<Models.ReservationHeader>()
select new ReservationDto(r.Current));
return inOneStep;
However, after splitting the above into two queries, with ToList() called on the results of the first, the code executes fine.
var step1 = (from r in session.Linq<Models.ReservationHeader>()
select r).ToList();
var step2 = from z in step1
select new ReservationDto(z.Current);
return step2;
Why does the single statement version raise an exception?
Thank you,
Ben
The reason that the first one does not work is because the whole query is getting sent to NHibernate, and (as the exception tells you) NHibernate expects something with ReservationDto to be IConvertible.
The two step process avoids this error, because by calling "ToList()" you cause the query to execute in NHibernate immediately without involving ReservationDto, and returning an object collection. Your second step is then simply operating on an object collection, and since NHibernate is no longer involved, you avoid the error.
In general, Linq uses delayed execution, with a few functions (such as ToList() ) forcing immediate evaluation. See http://devlicio.us/blogs/derik_whittaker/archive/2008/04/07/linq-and-delayed-execution.aspx
Related
Using requery version 1.5.0 ReactiveEntityStore for select calls.
But the compiler giving error for below call -
Observable<Result<Person>> result = mDataStore
.select(Person.class)
.where(Person.CATEGORY.eq(category))
.orderBy(Person.SEQUENCE.asc())
.get()
.observableResult();
Error details:
https://i.stack.imgur.com/bdPlY.png
I'm not sure about how you got that particular error message (maybe I can edit if you add more information about the actual classes involved).
However, it seems like you are mixing Result with ReactiveResult, what you want is probably:
// Supposing this is your definition of the data store:
ReactiveEntityStore<Person> mDataStore;
// Your result is going to be Reactive, next line is the one changed!
Observable<ReactiveResult<Person>> result = mDataStore
.select(Person.class)
.where(Person.CATEGORY.eq(category))
.orderBy(Person.SEQUENCE.asc())
.get()
.observableResult();
I'm working on a project where I'm converting Linq to SQL (which I admittedly very poorly understand) to Linq to Entity and have ran into an odd situation. The code below correctly returns results when evaluated against a class generated in the Linq to SQL designer but does not work when run against an Entity Framework entity. Specifically if any of the properties in the Or clauses are null, the process breaks with a Null Reference exception. I've tried techniques to check for null property and then say, pass a value I know can't be in the SearchTerm to short circuit around this but they just result in this LINQ returning all results from the entity in a way that I don't really understand either.
Return (From values In Location.getData _
Where (values.LocName.Contains(SearchTerm) _
Or values.Address.Contains(SearchTerm) _
Or values.Address2.Contains(SearchTerm) _
Or values.City.Contains(SearchTerm) _
Or values.State.Contains(SearchTerm) _
Or values.QIM.Contains(SearchTerm) _
Or values.MacID.Contains(SearchTerm) _
Or values.Phone.Contains(SearchTerm) _
Or values.PrimServ.Contains(SearchTerm) _
Or values.Zip.Contains(SearchTerm) _
Or values.Area.Contains(SearchTerm) _
Or values.Type.Contains(SearchTerm)
) And (values.Status <> "Closed" Or status_parm = "Closed")
Select values)
As you can probably guess the getData method on the entity class Location is basically using DbContext.SqlQuery to construct a query into the database and then this LINQ is being used to filter the results. I'm aware of several issues with this that make it less than ideal, but there are reasons it was written this way before I started the conversion that aren't easily changed.
E.g.
Where (values.LocName IsNot Nothing AndAlso values.LocName.Contains(SearchTerm)) OrElse
(values.Address IsNot Nothing AndAlso values.Address.Contains(SearchTerm))
So the answer I finally got working was to use ToLower
SearchTerm = SearchTerm.ToLower
Return (From values In Location.getData _
Where (values.LocName IsNot Nothing And Also values.LocName.ToLower.Contains(SearchTerm)
I would still like to understand two things:
Why is a check for null required when using LINQ to Entity where in LINQ to SQL it runs without issue and never hits a NullReference exception?
Why is LINQ's .Contains not case sensitive in LINQ to SQL but it is here? I've verified with 100% certainty this same code using LINQ to SQL does not throw NullReference exceptions ever, and does not require dealing with .Contains as a case sensitive function (so any casing of the SearchTerm will match to any casing of the result implicitly.)
I have a simple web application based on the Play Framework 2.3 (scala), which currently uses sqlite3 for the database. I'm sometimes, but not always, getting exceptions caused by inserting rows into the DB:
java.sql.SQLException: statement is not executing
at org.sqlite.Stmt.checkOpen(Stmt.java:49) ~[sqlite-jdbc-3.7.2.jar:na]
at org.sqlite.PrepStmt.executeQuery(PrepStmt.java:70) ~[sqlite-jdbc-3.7.2.jar:na]
...
The problem occurs in a few different contexts, all originating from SQL(statement).executeInsert()
For example:
val statementStr = "insert into session_record (condition_id, participant_id, client_timestamp, server_timestamp) values (%d,'%s',%d,%d)".format(conditionId,participantId,clientTime,serverTime)
DB.withConnection( implicit c => {
val ps = SQL(statement)
val pKey = populatedStatement.executeInsert()
// ...
}
When an exception is not thrown, pKey contains an option with the table's auto-incremented primary key. When an exception is thrown, the database's state indicate that the basic statement was executed, and if I take the logged SQL statement and try it by hand, it also executes without a problem.
Insert statements that aren't executed with "executeInsert" also work. At this point, I could just use ".execute()" and get the max primary key separately, but I'm concerned there might be some deeper problem I'm missing.
Some configuration details:
In application.conf:
db.default.driver=org.sqlite.JDBC
db.default.url="jdbc:sqlite:database/mySqliteDb.db"
My sqlite version is 3.7.13 2012-07-17
The JDBC driver I'm using is "org.xerial" % "sqlite-jdbc" % "3.7.2" (via build.sbt).
I ran into this same issue today with the latest driver, and using execute() was the closest thing to a solution I found.
For the sake of completion, the comment on Stmt.java for getGeneratedKeys():
/**
* As SQLite's last_insert_rowid() function is DB-specific not statement
* specific, this function introduces a race condition if the same
* connection is used by two threads and both insert.
* #see java.sql.Statement#getGeneratedKeys()
*/
Most certainly confirms that this is a hard to fix bug in the driver, due to SQLite's design, that makes executeInsert() not thread safe.
First it would be better not to use format for passing parameter to the statement, but using either SQL("INSERT ... {aParam}").on('aParam -> value) or SQL"INSERT ... $value" (with Anorm interpolation). Then if exception is still there I would suggest you to test connection/statement in a plain vanilla standalone Java test app.
I need PMD for processing the following statements using XPath.
1.before end of most outer try block there must be fillTrasactionStatus()
2.most outer try should have two catch with fatalException & throwable, having logException and fillTransactioStatus()
3.Interaction.begin() & fetchTransactionStatus() should be the first (This should be in their start of every public method exposed via interface)
My approach for the 1st question was...
//PrimaryPrefix [Name[#Image='fillTransactionStatus']]
[ancestor::TryStatement]
But how do I ensure that its for the outermost try block.
Please Help.
Does anyone have the faintest idea what this error means please and how to resolve it? All my research is drawing a blank, I can see how to set it on MSDN but it doesn't explain it in a way that explains to me what the issue is. If I remove some of my LINQ queries to set viewbag items then it seems to resolve it but the moment I set new ones and pass them into my view to generate a mail for MVCMailer it comes back. Not sure if its a viewbag issue or simply that I am calling too many linq queries to generate them to pass to the view.
I am very stuck (again)..........
Cheers,
Steve.
DbLimitExpression requires a collection argument.
Parameter name: argument
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: DbLimitExpression requires a collection argument.
Parameter name: argument
An example of the code is:
var VBSalutation = from A in context.Salutations
where A.SalutationId == policytransaction.SalutationId
select A.SalutationName;
ViewBag.Salutation = VBSalutation.FirstOrDefault();
This is repeated for various parameters and then passed to the view.
Well, I faced a similar problem and solved it. Problem was in WHERE clause: data type of left side equal operator (=) sign was not matching with data type of right side. So in your scenario:
where A.SalutationId == policytransaction.SalutationId
SalutationID of A might be an INT and SalutationId of policytransaction might be a string (This is how it was in my case).
I solved it by assigning policytransaction.SalutationId to an Int variable and using it:
int myIntVariable = Convert.ToInt16(policytransaction.SalutationId);
...//some code here
where A.SalutationId == myIntVariable;
Please also note that you cannot directly cast your variables directly in Linq else you'll get an error "LINQ to Entities does not recognize the method". You'll have to use a temp variable and then apply the where clause.
Try ViewBag.Salutation = VBSalutation.SingleOrDefault();