使用控制台:
1.数据库字符串
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <appSettings> <add key="IDBConfig" value="T2.SQLServer;T2.SQLServer.SQLServerHelper"/> <add key="UserDbContext" value="Data Source=.;Database=Test;Uid=sa;Pwd=sa" /> </appSettings> <connectionStrings> <add name="DbContext" connectionString="Data Source=.;Database=Test;Uid=sa;Pwd=sa" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>
2.方法
public class SQLHelper { private static string dbConnStr = ConfigurationManager.ConnectionStrings["DbContext"].ToString(); public static T Find<T>(int id) { Type type = typeof(T); object obj = Activator.CreateInstance(type); var propNames = type.GetProperties().Select(c => $"{c.Name}"); string props = string.Join(",", propNames); string sql = $"SELECT { props } FROM [{ type.Name }] WHERE ID={id}"; using (SqlConnection conn = new SqlConnection(dbConnStr)) { SqlCommand sqlCommand = new SqlCommand(sql,conn); conn.Open(); SqlDataReader reader = sqlCommand.ExecuteReader(); if (reader.Read()) { foreach (var prop in type.GetProperties()) { prop.SetValue(obj,reader[prop.Name]); } } } return (T)obj; } }
3.使用
var user = SQLHelper.Find<User>(1);
补充:
1)方法(注:调用放入Debug内的dll,但是仅限于.NET Framework,.Net Core好像不支持)
public class SimpleFactory { private static string config = ConfigurationManager.AppSettings["IDBConfig"]; public static dynamic CreateInstentce() { Assembly assembly = Assembly.Load("T2.SQLServer"); Type type = assembly.GetType("T2.SQLServer.SQLServerHelper"); dynamic dynamic = Activator.CreateInstance(type); return dynamic; } }
2)使用
dynamic db = SimpleFactory.CreateInstentce(); db.Query();
3)说明
dynamic是动态编译(不至于一开始就让编译器报错),程序执行后采取判断有没有Query方法
标签:string,C#,dynamic,ORM,static,泛型,type,public,Name From: https://www.cnblogs.com/dzw159/p/16908323.html