最近在项目中使用XPO时,遇到了这样的问题,在sql中有charindex方法
select * from table1 where charindex(col1, ';a;b;c;d;')<>0//col1 is a column in the table1
而在XPO中当我构造查询条件时却没有类似charindex的方法,后来在DevExpress的官方网站上提出了这样的问题,经过她们的帮助找到了实现charindex功能的方法。
以下是我的问题和她们的回复
Question:
By sql syntax, i can write this: select * from table1 where charindex(col1, ';a;b;c;d;')<>0 //col1 is a column in the table1
but in xpo,how can i realize this function( charindex('))?
if there have any way to do this, please help me.
thanks
Jet
Answered by Developer Express Team:
Hi Jet,
You can use the following code which creates a custom function:
class CustomCharIndexProvider : MSSqlConnectionProvider {
public CustomCharIndexProvider(IDbConnection connection, AutoCreateOption autoCreateOption)
: base(connection, autoCreateOption) {
}
public override string FormatFunction(FunctionOperatorType operatorType, params string[] operands) {
if (operatorType == FunctionOperatorType.Custom && operands.Length == 3 && operands[0] == CharindexFunction.CharindexFunctionName)
return String.Format("charindex({0}, {1})", operands[1], operands[2]);
return base.FormatFunction(operatorType, operands);
}
}
public class CharindexFunction : FunctionOperator {
public const string CharindexFunctionName = "charindex";
public CharindexFunction(CriteriaOperator expression1, CriteriaOperator expression2) : base(CharindexFunctionName, expression1, expression2) { }
}
Modify the Main function:
[STAThread]
static void Main() {
string connectionString = ""; // You should specify the connection string to your database.
XpoDefault.DataLayer = new SimpleDataLayer(new CustomCharIndexProvider(connectionString, AutoCreateOption.DatabaseAndSchema));
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Using:
private void Form1_Load(object sender, EventArgs e) {
// ...
CriteriaOperator criteria = new CharindexFunction(expression1, expression2);
XPCollection collection = new XPCollection(session1, objectType, criteria);
}
这里给大家分享一下,如果有类似的问题可以采用这种方法来解决。