玄铁剑

成功的途径:抄,创造,研究,发明...
posts - 128, comments - 42, trackbacks - 0, articles - 174

自定组合查询一则

Posted on 2008-06-28 23:38 玄铁剑 阅读(386) 评论(0)  编辑 收藏 引用 所属分类: asp.net

首先声明一个带一个属性的Attribute,用这个属性来存操作符

[AttributeUsage(AttributeTargets.Field)] //此属性只能用在Field上
public class OpAttribute : Attribute
{
private string _op = string.Empty;
public OpAttribute(string op)
{
_op = op;
}
public string Name
{
get { return _op; }
set { _op = value; }
}
}

然后在查询条件的类中加上这些Attribute

public class AttributeClass
{
[OpAttribute("=")]
public int MyProperty;
[OpAttribute("=")]
public string aa;
[OpAttribute("like")]
public string bb;
}

然后再调用一个组合sql语句的方法

AttributeClass ac = new AttributeClass();
ac.MyProperty = 11;
ac.aa = "abcd";
ac.bb = "ddd";
string sql="1=1";
Type type = typeof(AttributeClass);
foreach (System.Reflection.FieldInfo fieldInfo in type.GetFields())
{
foreach (Attribute at in fieldInfo.GetCustomAttributes(true))
{
OpAttribute att = at as OpAttribute;
if (att != null)
{
sql += " and " + fieldInfo.Name +" "+ att.Name+" "+ fieldInfo.GetValue(ac);
}
}
}
只有注册用户登录后才能发表评论。