Method 'Boolean Contains(System.String)' has no supported translation to SQL - sql

"Method 'Boolean Contains(System.String)' has no supported translation to SQL."
query is IsQueryable but this stopped working:
foreach (string s in collection1)
{
if (s.Length > 0)
{
query = query.Where(m => m.collection2.Contains(s));
}
}
UPDATE: it works when i make query "ienumerable" instead of iqueryable. What would be the way to get same result using linq instead of iterating through loop?

Try this:
query = query.Where(m => m.collection2.ToList().Contains(s));
^^^^^^^^

Take a look at this answer from stackoverflow.
It looks like the resulting query would need access to something that the database
has no way of reaching, because the info is in memory.

Since m.collection2 is in the database, don't use Contains. Use Any
m.collection2.Any(x => x == s)

It looks like the error you are seeing is coming from the collection collection 2. Have you tried wrappering the m.collection2 in another function which returns true or false? Is this LINQ syntax?

Related

CodeIgniter4 Model returning data results

I am starting to dabble in CI4's rc... trying to get a head of the game. I noticed that the Model is completely rewritten.
Going through their documentation, I need some guidance on how to initiate the equivalent DB query builder in CI4.
I was able to leverage return $this->findAll(), etc...
however, need to be able to be able to query w/ complex joins and also be able to return single records etc...
When trying something like
return $this->orderBy('import_date', 'desc')
->findColumn('import_date')
->first();
but getting error:
Call to a member function first() on array
Any help or guidance is appreciated.
Suppose you have a model instantiated as
$userModel = new \App\Models\UserModel;
Now you can use it to get a query builder like.
$builder = $userModel->builder();
Use this builder to query anything for e.g.
$user = $builder->first();
Coming to your error.
return $this->orderBy('import_date', 'desc')
->findColumn('import_date');
findColumn always returns an array or null. So you can't use it as object. Instead you should do following.
return $this->orderBy('import_date', 'desc')->first();

Check if an existing value is in a database

I was wondering how I would go about checking to see if a table contains a value in a certain column.
I need to check if the column 'e-mail' contains an e-mail someone is trying to register with, and if something exists, do nothing, however, if nothing exists, insert the data into the database.
All I need to do is check if the e-mail column contains the value the user is registering with.
I'm using the RedBeanPHP ORM, I can do this without using it but I need to use that for program guidelines.
I've tried finding them but if they don't exist it returns an error within the redbean PHP file. Here's the error:Fatal error: Call to a member function find() on a non-object in /home/aeterna/www/user/rb.php on line 2433
Here's the code that I'm using when trying this:
function searchDatabase($email) {
return R::findOne('users', 'email LIKE "' . $email . '"');
}
My approach on the function would be
function searchDatabase($email) {
$data = array('email' => $email);
$user = R::findOne('users', 'email LIKE :email, $data);
if (!empty($user)) {
// do stuff here
} // end if
} // end function
It's a bit more clean and in your function
Seems like you are not connected to a database.
Have you done R::setup() before R::find()?
RedBeanPHP raises this error if it can't find the R::$redbean instance, the facade static functions just route calls to the $redbean object (to hide all object oriented fuzzyness for people who dont like that sort of thing).
However you need to bootstrap the facade using R::setup(). Normally you can start using RB with just two lines:
require('rb.php'); //cant make this any simpler :(
R::setup(); //this could be done in rb.php but people would not like that ;)
//and then go...
R::find( ... );
I recommend to check whether the $redbean object is available or whether for some reason the code flow has skipped the R::setup() boostrap method.
Edited to account for your updated question:
According to the error message, the error is happening inside the function find() in rb.php on line 2433. I'm guessing that rb.php is the RedBean package.
Make sure you've included rb.php in your script and set up your database, according to the instructions in the RedBean Manual.
As a starting point, look at what it's trying to do on line 2433 in rb.php. It appears to be calling a method on an invalid object. Figure out where that object is being created and why it's invalid. Maybe the find function was supplied with bad parameters.
Feel free to update your question by pasting the entirety of the find() function in rb.php and please indicate which line is 2433. If the function is too lengthy, you can paste it on a site like pastebin.com and link to it from here.
Your error sounds like you haven't done R::setup() yet.
My approach to performing the check you want would be something like this:
$count = count(R::find('users', 'email LIKE :email', array(':email' => $email)));
if($count === 0)
{
$user = R::dispense('users');
$user->name = $name;
$user->email = $email;
$user->dob = $dob;
R::store($user);
}
I don't know if it is this basic or not, but with SQL (using PHP for variables), a query could look like
$lookup = 'customerID';
$result = mysql_fetch_array(mysql_query("SELECT columnName IN tableName WHERE id='".$lookup."' LIMIT 1"));
$exists = is_null($result['columnName'])?false:true;
If you're just trying to find a single value in a database, you should always limit your result to 1, that way, if it is found in the first record, your query will stop.
Hope this helps

Can I use SQL functions in NHibernate QueryOver?

I have been searching the internet and can't find an example on how to use the queryover of nhibernate 3.0
For example I would like to use the string functions on the where clause of the queryover
ex:
var item = Query.Where(x => x.Name.ToLower() == name.ToLower()).FirstOrDefault();
But this doesn't work, because nhibernate can't understand the ToLower, so how can extend the dialect in a way that this becomes possible?
session.QueryOver<Foo>()
.Where(Restrictions.Eq(
Projections.SqlFunction("lower", NHibernateUtil.String,
Projections.Property<Foo>(x => x.Name)),
name.ToLower()))
should get you SQL like where lower(Name) = #p0
I believe it works at least in the build I am using (version 3.0.0.4000)... below is my example...
var reasons = _session.Query<Reason>();
var myReason = (from r in reasons
where r.IsCritical
&& r.ReasonCode.ToUpper() == reasonCode.ToUpper()
select r).FirstOrDefault();
Give it a shot and let me know if it works for you...

LINQ display row numbers

I simply want to include a row number against the returned results of my query.
I found the following post that describes what I am trying to achieve but gives me an exception
http://vaultofthoughts.net/LINQRowNumberColumn.aspx
"An expression tree may not contain an assignment operator"
In MS SQL I would just use the ROWNUMBER() function, I'm simply looking for the equivalent in LINQ.
Use AsEnumerable() to evaluate the final part of your query on the client, and in that final part add a counter column:
int rowNo = 0;
var results = (from data in db.Data
// Add any processing to be performed server side
select data)
.AsEnumerable()
.Select(d => new { Data = d, Count = ++rowNo });
I'm not sure whether LINQ to SQL supports it (but it propably will), but there's an overload to the Queryable.Select method that accepts an lambda with an indexer. You can write your query as follows:
db.Authors.Select((author, index) => new
{
Lp = index, Name = author.Name
});
UPDATE:
I ran a few tests, but unfortunately LINQ to SQL does not support this overload (both 3.5sp1 and 4.0). It throws a NotSupportedException with the message:
Unsupported overload used for query
operator 'Select'.
LINQ to SQL allows you to map a SQL function. While I've not tested this, I think this construct will work:
public partial class YourDataContext : DatContext
{
[Function(Name = "ROWNUMBER")]
public int RowNumber()
{
throw InvalidOperationException("Not called directly.");
}
}
And write a query as follows:
from author in db.Authors
select new { Lp = db.RowNumber(), Name = author.Name };

Linq to Nhiberate - Where clause

I have tried to find an answer to this, but could not find one in google. Probably not searching the correct terms, so thought I would ask here.
The following returns all my contacts, not the ones that equal the adjusterType sent in.
var contacts = from c in session.Linq<Contact>() select c;
contacts.Where(c => c.ContactAdjuster.AdjusterType == adjusterType);
The following does return the expected results. It does return only the contacts that meet the adjusterType. I believe it is my lack of understanding of LINQ.
var contacts = from c in session.Linq<Contact>() select c;
contacts = contacts.Where(c => c.ContactAdjuster.AdjusterType == adjusterType);
Thanks in advance.
the Where clause returns an IEnumerable in your case an IEnumerable. This is the standard LiNQ and C# behavior. Instead of modifying your collection it is returning a new collection based on your where clause.
I suppose NHibernate LiNQ should mimic this.
CatZ is absolutely right, you are not modifying the "contacts" collection/enumerable you are creating a new based on the existing, which is why your second statement works.
But instead of just repeating CatZ statement, here is a little add-on:
You can write this in one statement though
var contacts =
from c in session.Linq<Contact>()
where c.ContactAdjuster.AdjusterType == adjusterType
select c;
Or simply
var contacts = session.Linq<Contact>().Where(c => c.ContactAdjuster.AdjusterType == adjusterType);