您的位置:首页 > 数据库

通过自定义注解反射生成SQL语句

2016-03-18 11:41 567 查看
----------------------------------------Program.cs----------------------------------------

using System;
using System.Collections.Generic;
using System.Text;
//反射命名空间
using System.Reflection;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Student stu = new Student(1, "Jong_Cai", 21);
Insert(stu);
}

public static void Insert(Object obj)
{
String fileds = null;
String values = null;

Type type = obj.GetType();
//获取类名
String className = type.Name;
//获取所有公有属性
PropertyInfo[] info = type.GetProperties();

foreach (PropertyInfo var in info)
{
//取得属性的特性标签,false表示不获取因为继承而得到的标签
Object[] attr = var.GetCustomAttributes(false);
if (attr.Length > 0)
{
//从注解数组中取第一个注解(一个属性可以包含多个注解)
MyAttribute myattr = attr[0] as MyAttribute;
if (myattr.PrimaryKey == true)
{
continue;
}
}
fileds += var.Name + ",";
values += "'" + var.GetValue(obj, null) + "',";
}

fileds = fileds.Substring(0, fileds.Length - 1);
values = values.Substring(0, values.Length - 1);
String sql = "insert into {0}({1}) values({2})";
sql = String.Format(sql, className, fileds, values);
Console.WriteLine(sql);
}
}
}

-----------------------------------------------MyAttribute.cs---------------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
//自定义注解类
class MyAttribute: Attribute
{
public Boolean PrimaryKey = false;
public String Type = null;
}
}

-------------------------------------------Student.cs--------------------------------------------

using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
public class Student
{
private int _id;
[My(PrimaryKey = true, Type = "自动增长")] //自定义注解
public int Id
{
get { return _id; }
set { _id = value; }
}

private String _name;
[My(PrimaryKey = false, Type = "名字")] //自定义注解
public String Name
{
get { return _name; }
set { _name = value; }
}

private int _age;
[My(PrimaryKey = false, Type = "年龄")] //自定义注解
public int Age
{
get { return _age; }
set { _age = value; }
}

public Student(int id, String name, int age)
{
this._id = id;
this._name = name;
this._age = age;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: