一、打开VS2017,新建一个控制台项目:ReflactionDemo1
二、新建类库:ReflactionDemo1.Model
1.在类库下面新建抽象类:BaseModel.cs
public abstract class BaseModel
{
[PrimaryKey("ID")]
public virtual int ID { get; set; }
}
2.新建实体类:Students.cs 并且继承:BaseModel.cs
public class Students : BaseModel
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
3.新建特性扩展类:PrimaryKeyAttribute.cs 用于过滤主键ID
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
public class PrimaryKeyAttribute : Attribute
{
public PrimaryKeyAttribute(string keyName)
{
KeyName = keyName;
}
public string KeyName { get; set; }
}
三、新建类库:ReflactionDemo1.IDBSqlserver
1.新建接口:IDbHelper.cs 并添加增删查等方法体
public interface IDbHelper
{
bool Add<T>(T t) where T : BaseModel;
T Get<T>(int Id) where T: BaseModel;
bool Delete<T>(int id) where T : BaseModel;
List<T> GetList<T>() where T : BaseModel;
}
四、新建类库:ReflactionDemo1.DBSqlserver
1.新建类:DbHelper.cs 用于继承接口:IDbHelper.cs ,并实现接口的方法
public class DbHelper : IDbHelper
{
private static string connectionString = ConfigurationManager.AppSettings["ConnectionString"];
public bool Add<T>(T t) where T : BaseModel
{
var type = typeof(T);
var properties = type.GetProperties().Where(s => !s.GetCustomAttributes(typeof(PrimaryKeyAttribute)).Any()).ToList();
var columnsName = string.Join(",", properties.Select(s => s.Name));
var columnsParameters = string.Join(",", properties.Select(s => $"@{s.Name}"));
var parameters = new List<SqlParameter>(properties.Select(s => new SqlParameter($"@{s.Name}", s.GetValue(t))));
string sql = $"INSERT INTO [{type.Name}]({columnsName}) VALUES({columnsParameters})";
return ExecuteSql(sql, cmd =>
{
foreach (var parameter in parameters)
{
cmd.Parameters.Add(parameter);
}
return cmd.ExecuteNonQuery() > 0;
});
}
public bool Delete<T>(int id) where T : BaseModel
{
var type = typeof(T);
string sql = $"delete from [{type.Name}] where id={id}";
return ExecuteSql(sql, cmd =>
{
return cmd.ExecuteNonQuery() > 0;
});
}
public T ExecuteSql<T>(string sql, Func<IDbCommand, T> func)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
IDbCommand cmd = conn.CreateCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
return func(cmd);
}
}
public T Get<T>(int Id) where T : BaseModel
{
var t = Activator.CreateInstance<T>();
var type = typeof(T);
var properties = type.GetProperties().ToList();
var columnsName = string.Join(",", properties.Select(s => s.Name));
string sql = $"SELECT {columnsName} FROM [{type.Name}] WHERE id={Id}";
return ExecuteSql(sql,cmd =>
{
IDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
SetProperties(properties, reader, t);
}
return t;
});
}
public List<T> GetList<T>() where T : BaseModel
{
List<T> list = new List<T>();
var type = typeof(T);
var properties = type.GetProperties().ToList();
var columnsName = string.Join(",", properties.Select(s => s.Name));
string sql = $"SELECT {columnsName} FROM [{type.Name}]";
return ExecuteSql(sql,cmd =>
{
IDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var t = Activator.CreateInstance<T>();
SetProperties(properties, reader, t);
list.Add(t);
}
return list;
});
}
private static void SetProperties<T>(List<PropertyInfo> properties, IDataReader reader, T t)
{
foreach (var property in properties)
{
if (reader[property.Name] != DBNull.Value)
{
property.SetValue(t, reader[property.Name]);
}
}
}
五、在控制台程序ReflactionDemo1
1.在App.config 配置文件里面配置
<appSettings>
<!--程序集配置-->
<add key="DbConfig" value="ReflactionDemo1.DBSqlserver,ReflactionDemo1.DBSqlserver.DbHelper"/>
<!--数据库字符串连接-->
<add key="ConnectionString" value="Server=DESKTOP-6IQUA2VFMM;Database=School;User ID=sa;Password=123456;"/>
</appSettings>
2.新建类:SimpleFactory.cs 用于实现反射动态创建实例
public class SimpleFactory
{
public static string dllName = ConfigurationManager.AppSettings["DbConfig"].Split(',')[0];
public static string typeName= ConfigurationManager.AppSettings["DbConfig"].Split(',')[1];
public static IDbHelper CreateInstance()
{
Assembly assembly = Assembly.Load(dllName);
var type = assembly.GetType(typeName);
var o = Activator.CreateInstance(type);
return (IDbHelper)o;
}
}
六、在控制台调用方法测试
class Program
{
static void Main(string[] args)
{
IDbHelper dbHelper = SimpleFactory.CreateInstance();
Students student = new Students
{
Address = "测试",
Age = 20,
Name = "admin"
};
var model = dbHelper.Add<Students>(student);
}
}