Convert SQL to Linq expression - c#

I'm looking a way to convert this query:
Select *
From Tasks
Where Addresses_Street1+' '+Addresses_Street2+' '+Addresses_City +' '+Addresses_ZipCode Like '%'+replace(ltrim(rtrim('Leon Deladriere 15')),' ','%')
to a Linq C# expression.
I know that Contains() and Trim() can be use for the method but how to handle the replace ' ' by '%' ?
This expression is used to provide to user one single input with an address and look into multiples columns to find a matching one.
I use Linqpad but I doesn't see equivalent in Linq

You can try.
(from r in Tasks where SqlMethods.Like(
r.Addresses_Street1 + " " +
r.Addresses_Street2 + " " +
r.Addresses_City + " " +
r.Addresses_ZipCode,
"%Leon Deladriere 15".Trim().Replace(" " , "%"))
select r)
Note, LinqSql is smart enough to know that it can do the Trim and Replace locally rather than asking Sql to do it.
However if you use a field rather than a constant, eg
(from r in Task where SqlMethods.Like( ... ,
r.Addresses_Street1 + " " +
r.Addresses_Street2 + " " +
r.Addresses_City + " " +
r.Addresses_ZipCode,
r.AnotherField.Trim().Replace(" " , "%"))
select r)
then this will ask sql to do the trim and replace.

Try this:
var user = "Leon Deladriere 15".Trim();
Tasks.Where(t => (t.Addresses_Street1 + t.Addresses_Street2 + t.Addresses_City + t.Addresses_ZipCode).Contains(user));

Related

Error : in my query i am using multiple variables in c#

i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting
Here is the query
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
Exception image
here the image for exception i am getting after run this query
On your ...'"+x+"... you forgot to close the single quotes. You open them but you never close them after you add the X variable to your query. All SQL is seeing is "'0," which is invalid syntax.
I recommend use SQLparameters to avoid sql injection but your error is you forgot to close the single quotes it shoud be like this '"+cls + "'
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '" + id + "','"+s.session+"','" + title.Text + "','" + from.Value.Date.ToString("yyyy-MM-dd") + "','" + to.Value.Date.ToString("yyyy-MM-dd")+"' , '"+c.class_name+"','" + x + "','" + x + "' from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
I don't know why you need that on select columns. and you provided insufficient information and code on your question.

How do I solve the SQL(query) missing database error?

Error Code : 1 (SQLITE_ERROR)
Caused By : SQL(query) error or missing database.
(near "=": syntax error (code 1): , while compiling: DELETE FROM notesWHEREid='1')
This is the error i am getting:
This is the part of my database handler that is the source of this error:
public void deleteNote(String id) {
SQLiteDatabase db = this.getWritableDatabase();
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";
db.execSQL(deleteQuery);
db.close();
}
If you are using C# 6.0, using interpolated strings makes life much easier for strings concatenation, avoiding such silly errors:
String deleteQuery= $"DELETE FROM {DatabaseValues.TABLE_NOTES} WHERE {DatabaseValues.NOTES_ID} = id";
Note: $ operator is available in C# 6.0. Also you should take a look into how to build parameterized queries because passing parameters like this can expose you to SQL injection.
Change your following statement:
String deleteQuery="DELETE FROM " + DatabaseValues.TABLE_NOTES + "WHERE" + DatabaseValues.NOTES_ID + "= '" + id + "'";
to
String deleteQuery= "DELETE FROM " + DatabaseValues.TABLE_NOTES + " WHERE " + DatabaseValues.NOTES_ID + " = '" + id + "'";
Actually you are combining the table name with where clause. You need to add a space before and after WHERE Clause like " Where "
Hope it helps.

How to Convert ADO.NET to LINQ?

"SELECT TOP " + this.mintPageSize + " * FROM tblGroupDetail WHERE GroupDetailId NOT IN " + "(SELECT TOP " + intSkip + " GroupDetailId FROM tblGroupDetail)")
How Convert this Query to Linq.SomeOne tell me with Code?i have tried
var innerQuery = (from fb in db.tblGroupDetails where fb.GroupDetailID select fb).Take(this.mintPageSize);
var result = from f in db.tblGroupDetails where innerQuery.Contains(f.GroupDetailID) select f;
I suspect you just need:
var query = db.GroupDetail
.OrderBy(...) // You really need an ordering
.Skip(intSkip)
.Take(mintPageSize);
You should work out what ordering you want, otherwise "the first N" doesn't have any meaning.
That's not a translation of your query so much as your intent - you should check what SQL it generates.

Access Database select more than one row in c#

I have been following this site for basic Access database implementation in C#
http://www.homeandlearn.co.uk/csharp/csharp_s12p12.html
I want to search more than one row. This code works for one row.
string searchFor = txtFurniture.Text;
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor + "'");
How do I add in additional rows to check? I have tried something like
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + "Style='" + searchFor + "'");
but this fails.
you need to add and condition
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor +
"' and Style='" + searchFor + "'");
In addition you can check this answer might help you to understand easily : Datatable select with multiple conditions
You mean an additional field to check.
Make a condition that looks like this:
Finish='something' and Style='something'
using:
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor + "' and Style='" + searchFor + "'");
As referenced in the documentation for the DataTable.Select method, the documentation for the DataColumn.Expression property describes the syntax to be used with the filterExpression parameter. In your case, use And to create a compound expression with your two conditions:
returnedRows = ds1.Tables["Furniture"].Select("Finish='" + searchFor + "' And Style='" + searchFor2 + "'");
...or more readably...
string filterExpression = string.Format("Finish='{0}' And Style='{1}'", searchFor, searchFor2);
DataRow[] returnedRows = ds1.Tables["Furniture"].Select(filterExpression);

Column with same name in multiple tables causing problem in SubSonic Select

there are other question (at least 2 I've seen them) similar to this but I'm not able to solve this using them.
Now the problem: I've 3 table from which I need to select 4 columns only. I'm using InnerJoin and it is working perfectly. Problem starts when I add a Where to this Select. I've a column named "Name" in two tables. If I add simply the
.Where("Name").Like("A%")
It says "... ambiguous column name.."
If I use fully qualified column name (with table prefixed to column name) it says must declare parameter #TABLE_NAME
SqlQuery sq = new Select(Tables.TableOne + "." + TableOne.Columns.MemberId +
" AS MemberId",
Tables.TableTwo + "." + TableTwo.Columns.Name + " AS MemberName",
Tables.TableOne + "." + TableOne.Columns.ExpiryOn + " AS MembershipExpiresOn",
Tables.TableFour + "." + TableFour.Columns.Name + " AS Country")
.From(DAL.Tables.TableOne)
.InnerJoin(Tables.TableTwo)
.InnerJoin(Tables.TableThree)
.InnerJoin(Tables.TableFour, TableFour.Columns.CountryCode,
Tables.TableThree, TableThree.Columns.CountryOfBirth).
sq.Where(Tables.TableTwo + "." + TableTwo.Columns.Name).Like("A%");
I've tried to pass hard-coded string also but nothing works!
If you pass in the column object to the Where statement SubSonic will use it's fully qualified name instead of building a string. You can find the column on the object as a static property, so in this case if you have an object called "TableOne" you can use "TableOne.NameColumn" and pass that into the Where():
...
sq.Where(TableTwo.NameColumn).Like("A%");
Does the following query work, I'm assuming you're using 2.2:
SqlQuery sq = new Select(TableOne.Columns.MemberId + " AS MemberId",
TableTwo.Columns.Name + " AS MemberName",
TableOne.Columns.ExpiryOn + " AS MembershipExpiresOn",
TableFour.Columns.Name + " AS Country")
.From(TableOne.Schema)
.InnerJoin(TableTwo.Schema)
.InnerJoin(TableThree.Schema)
.InnerJoin(TableFour.Schema)
.Where(TableTwo.Columns.Name).Like("A%");
I haven't used it ever,
but have your tried to change your last line to:
sq.WhereExpression(Tables.TableTwo + "." + TableTwo.Columns.Name + " LIKE 'A%');

Categories

Resources