Entity SQL Datetime Syntax error - entity-framework

Anyone know What is wrong with my syntax here? I am making dynamic eSQL Queries and running into an error when trying to make where condition for DateTime data type. This is the error:
The query syntax is not valid. Near term '2011', line 1, column 135.
If it matters the DateTime type in my entity is actually nullable DateTime?
However, I thought this is the correct syntax from everything I've read.
Here is the code:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>()
{
new EntityFilter<StudyFirstRead> { PropertyName = "username", OpType = ExpressionType.Equal, Value = "cwoodhouse" },
new EntityFilter<StudyFirstRead> { PropertyName = "FirstRead", OpType = ExpressionType.LessThan, Value = "DATETIME'2011-02-01 00:00'" }
};
Where EntityFilter is:
public class EntityFilter<T>
{
public string PropertyName { get; set; }
public ExpressionType OpType { get; set; }
public object Value { get; set; }
And I am building dynamic queries like so:
StringBuilder builder = new StringBuilder();
int counter = 0;
string baseStr = #"SELECT VALUE val FROM " + contextName + "." + tableName + " AS val WHERE val.";
builder.Append(baseStr);
foreach (EntityFilter<T> filter in filters)
{
//builder.Append(filter.PropertyName + " " + filter.OpTypeString() + " #p" + counter);
builder.Append(filter.PropertyName + " " + filter.OpTypeString() + "'" + filter.Value + "'");
counter++;
if (counter < filters.Count)
builder.Append(" AND val.");
else
{
break;
}
}
return builder.ToString();

It actually is the correct syntax for entity SQL (different than regular SQL or T-SQL).
Turns out the problem was too many single quotes, because I had them in both the EntityFilter object and the method that built the dynamic query.

according to you code the end of your SQL statement would produce something like
AND val.FirstRead = 'DATETIME'2011-02-01 00:00''
when executed you will get error
Error 102: Incorrect syntax near '2011'.
obviously that is not syntactically correct SQL, the quick fix whould be to have your filters collection as such:
List<EntityFilter<FirstRead>> filters = new List<EntityFilter<FirstRead>>() {
new EntityFilter<StudyFirstRead> {
PropertyName = "username",
OpType = ExpressionType.Equal,
Value = "cwoodhouse"
}, new EntityFilter<StudyFirstRead> {
PropertyName = "FirstRead",
OpType = ExpressionType.LessThan,
Value = "2011-02-01 00:00"
}
};

Related

Using Dapper and Postgresql - citext data type

I'm not sure if there is a way to support this, but I'm having trouble getting Dapper to map string parameter values to the Postgresql citext data type as it seems to be using the text type.
In particular, I'm trying to call a function that takes in citext parameters - the error I get back is:
var c = ConnectionManager<T>.Open();
string sql = #"select * from ""dbo"".""MyFunction""(#schemaName, #tableName);";
var param = new
{
schemaName = schema,
tableName = table
};
string insecureSalt = c.QueryMultiple(sql, param).Read<string>().FirstOrDefault();
ConnectionManager<T>.Close(c);
Error: Npgsql.PostgresException: 42883: function dbo.MyFunction(text, text) does not exist.
The signature that would match is function dbo.MyFunction(citext, citext) so clearly it can't find it using the default mapping.
According to Npgsql - http://www.npgsql.org/doc/types.html I need to be able to specify NpgsqlDbType.Citext as the type but I can't find a way to do this using Dapper.
Solved thanks to answer from Shay, complete solution here:
var c = ConnectionManager<T>.Open();
string sql = #"select * from ""dbo"".""MyFunction""(#schemaName, #tableName);";
var param = new
{
schemaName = new CitextParameter(schema),
tableName = new CitextParameter(table)
};
string insecureSalt = c.QueryMultiple(sql, param).Read<string>().FirstOrDefault();
ConnectionManager<T>.Close(c);
public class CitextParameter : SqlMapper.ICustomQueryParameter
{
readonly string _value;
public CitextParameter(string value)
{
_value = value;
}
public void AddParameter(IDbCommand command, string name)
{
command.Parameters.Add(new NpgsqlParameter
{
ParameterName = name,
NpgsqlDbType = NpgsqlDbType.Citext,
Value = _value
});
}
}
You probably need to create create a CitextParameter which extends ICustomQueryParameter. This API allows you to pass an arbitrary DbParameter instance to Dapper - in this case it would be an instance of NpgsqlParameter with its NpgsqlDbType set to Citext.
Something like this should work:
class CitextParameter : SqlMapper.ICustomQueryParameter
{
readonly string _value;
public CitextParameter(string value)
{
_value = value;
}
public void AddParameter(IDbCommand command, string name)
{
command.Parameters.Add(new NpgsqlParameter
{
ParameterName = name,
NpgsqlDbType = NpgsqlDbType.Citext,
Value = _value
});
}
}
When you write the SQL query, you can cast the parameter value like cast(#param as citext).
in my case below worked correctly. (usr is a class object)
string sql = "select * from users where user_name = cast(#user_name as citext) and password = #password;";
IEnumerable<users> u = cnn.Query<users>(sql, usr);
In your case, you can change the query like below and see if that works
string sql = #"select * from ""dbo"".""MyFunction""(cast(#schemaName as citext), cast(#tableName as citext));";

Postgresql update - Using ArrayList

I am getting an exception on update of postgres:
org.postgresql.util.PSQLException: Can't infer the SQL type...
Here is the code where in I build the sql statement dynamically and append the params:
public Boolean update(UserData usrData){
String sqlUpdateUser = "UPDATE \"USER\" ";
String sqlSetValues = "SET";
String sqlCondition = "Where \"USER_ID\" = ? ";
List<Object> params = new ArrayList<Object>();
List<Integer> types = new ArrayList<Integer>();
if(usrData.getFirstName() != null){
sqlSetValues = sqlSetValues.concat(" \"FIRST_NAME\" = ? ").concat(", ");
params.add(usrData.getFirstName());
types.add(Types.VARCHAR);
}
if(usrData.getMiddleName() != null){
sqlSetValues = sqlSetValues.concat("\"MIDDLE_NAME\" = ? ");
params.add(usrData.getMiddleName());
types.add(Types.VARCHAR);
}
params.add(usrData.getUserId());
types.add(Types.BIGINT);
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
sqlUpdateUser = sqlUpdateUser.concat(sqlSetValues).concat(sqlCondition);
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, updateParams, paramTypes);
if(rowsAffected > 0){
return Boolean.TRUE;
}else{
return Boolean.FALSE;
}
}
And table schema for the USER table is:
"FIRST_NAME" character varying(50),
"MIDDLE_NAME" character varying(50),
If I do an update statically without using the collection, but by using Array, I see no issue.
Code snipped using arrays:
Object[] param = { usrData.getFirstName(), usrData.getMiddleName(), usrData.getUserId() };
int[] type = { Types.VARCHAR, Types.VARCHAR, Types.BIGINT };
int rowsAffected = this.jdbcTemplate.update(sqlUpdateUser, param, type);
Am I missing something?
Thanks
K
Move these lines
Object[] updateParams = new Object[params.size()];
updateParams = params.toArray(updateParams);
Integer[] paramTypes = new Integer[types.size()];
paramTypes = types.toArray(paramTypes);
beneath
params.add(usrData.getUserId());
types.add(Types.INTEGER);
In your case you are missing to add usrData.getUserId() in updateParams.

DbExtensions - How to create WHERE clause with OR conditions?

I'm trying to create WHERE clause with OR conditions using DbExtensions.
I'm trying to generate SQL statement which looks like
SELECT ID, NAME
FROM EMPLOYEE
WHERE ID = 100 OR NAME = 'TEST'
My C# code is
var sql = SQL.SELECT("ID, FIRSTNAME")
.FROM("EMPLOYEE")
.WHERE("ID = {0}", 10)
.WHERE("NAME = {0}", "TEST");
How do I get the OR seperator using the above mentioned DbExtensions library?
I have found a definition for logical OR operator here
public SqlBuilder _OR<T>(IEnumerable<T> items, string itemFormat, Func<T, object[]> parametersFactory) {
return _ForEach(items, "({0})", itemFormat, " OR ", parametersFactory);
}
And some code examples here
public SqlBuilder Or() {
int[][] parameters = { new[] { 1, 2 }, new[] { 3, 4} };
return SQL
.SELECT("p.ProductID, p.ProductName")
.FROM("Products p")
.WHERE()
._OR(parameters, "(p.CategoryID = {0} AND p.SupplierID = {1})", p => new object[] { p[0], p[1] })
.ORDER_BY("p.ProductName, p.ProductID DESC");
}
I think (by analogy with example) in your case code should be something like this (but I can't test it for sure):
var params = new string[] { "TEST" };
var sql = SQL.SELECT("ID, FIRSTNAME")
.FROM("EMPLOYEE")
.WHERE("ID = {0}", 10)
._OR(params, "NAME = {0}", p => new object[] { p })
Hope this helps :)
By the way... have you tried this way?
var sql = SQL.SELECT("ID, FIRSTNAME")
.FROM("EMPLOYEE")
.WHERE(string.Format("ID = {0} OR NAME = '{1}'", 10, "TEST"))
It's simpler than you think:
var sql = SQL
.SELECT("ID, FIRSTNAME")
.FROM("EMPLOYEE")
.WHERE("(ID = {0} OR NAME = {1})", 10, "TEST");
One can use:
.AppendClause("OR", ",", "NAME = {0}",new object[]{"TEST"});

Ado.net Update Command is successful but database is not updated

The following code executes successfully and the return value of cmd.ExecuteNonQuery returns 1 indicating the row was successfully updated but the database is not truly updated. How could that be? I'm using sqlserver2008.
public string updatePost(string id, string head, string body)
{
connection = new SqlConnection(connString);
string cmdStr = "update News set Header = '"+head+"' , [Text] = '"+body+"' where Id = "+int.Parse(id)+"";
string msg = String.Empty;
try
{
connection.Open();
SqlCommand cmd = new SqlCommand(cmdStr, connection);
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:"+id+"' was successfully updated. Rows effected:"+effected+"";
}
catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
finally
{
connection.Close();
}
return msg;
}
Try this, this fixes some problems (like sql-injection), perhaps also your update issue:
public string UpdatePost(string id, string head, string body)
{
string msg = "";
string cmdStr = "update News set Header = #header, [Text] = #body where Id = #id";
using (var con = new SqlConnection(connString))
{
try
{
con.Open();
using (var cmd = new SqlCommand(cmdStr, con))
{
cmd.Parameters.AddWithValue("#header", head);
cmd.Parameters.AddWithValue("#body", body);
cmd.Parameters.AddWithValue("#id", int.Parse(id));
int effected = cmd.ExecuteNonQuery();
msg += "The 'News Post - id:" + id + "' was successfully updated. Rows effected:" + effected + "";
}
} catch (Exception ex)
{
msg = "The attempt to update the 'News Post - id'" + id + " failed with message: " + ex.Message;
}
}
return msg;
}

How to write a dynamic where 'like' query in Entity framework?

Here is my code:
//order my baselist is context.Entity
public static GridData Getdata<T>(ObjectSet<T> baseList,
int currentPage,
int rowsPerPage,
string sortcolumn,
string sortord,
string searchQuery,
string searchColumns)where T: class{
var query = baseList.OrderBy("it." + sortcolumn + " " + sortord);
string strPredicate = string.Empty;
if (!string.IsNullOrEmpty(searchColumns))
{
strPredicate = "it." + searchColumns + " LIKE #" + searchColumns + " ";
query = baseList.Where(strPredicate, new ObjectParameter(searchColumns, searchQuery)).OrderBy("it." + sortcolumn + " " + sortord);
}
}
My problem is i am trying to write down or form a like query in entity framework and seems like it does not support it.
You can use .Contains which is the LIKE operator equivalent in entity framework.
you can use this
query = baseList.Where(baseli=>baseli.Contains(searchColumns )).OrderBy("it." + sortcolumn + " " + sortord);
:)