前情提要:由于是老项目,引用的数据库Ngpsql.dll 2.0.6 文件版本太老,直接升级dll文件会导致很多以前的接口用不过,sql语句执行报错。所以暂时升级不了。用不了微软提供的EntityFramework框架,进入正题
首先定义标签
public class TableAttribute : Attribute
{
public string TableName { get; set; }
}
public class Column : Attribute
{
public string name { get; set; }
public Column(string name)
{
this.name = name;
}
}
public class PK : Attribute
{
public PK() { }
}
public class Ignore : Attribute
{
public Ignore() { }
}
public class ForeignKey : Attribute
{
public string column { get; set; }
public ForeignKey(string column)
{
this.column = column;
}
}
public class CollectionQuery : Attribute {
public string column { get; set; }
public CollectionQuery(string column)
{
this.column = column;
}
}
然后就是框架实现模块
public class ByuHealthORM {
private string connstring = null;
public ByuHealthORM(string connstring) {
this.connstring = connstring;
}
public List<T> Query<T>(string sqlstring) {
try {
List<T> result = new List<T>();
using (NpgsqlConnection conn = new NpgsqlConnection(this.connstring)) {
conn.Open();//打开数据库
NpgsqlCommand cmd = new NpgsqlCommand(sqlstring, conn);
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
object obj = SetModel(typeof(T), reader);
result.Add((T)obj);
}
}
}
return result;
}
catch (Exception e)
{
throw e;
}
}
private object GetModel(Type tp, string sqlstring)
{
try
{
object obj = null;
using (NpgsqlConnection conn = new NpgsqlConnection(this.connstring))
{
conn.Open();
NpgsqlCommand cmd = new NpgsqlCommand(sqlstring, conn);
NpgsqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
obj = SetModel(tp, re