当前位置:
首页 > temp > 简明python教程 >
-
C# ORM学习笔记:使用特性+反射实现简单ORM(3)
/// 根据实体返回主键
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static string GetKey<TEntity>(TEntity entity) where TEntity : class
{
Type entityType = entity.GetType();
string strKey = Convert.ToString(_HashKey[entityType.FullName]);
if (strKey == "")
{
if (entityType.GetCustomAttributes(typeof(DataTableAttribute), false)[0] is DataTableAttribute dtAttr)
{
strKey = dtAttr.Key;
}
else
{
throw new Exception(entityType.ToString() + "未设置DataTable特性。");
}
_HashKey[entityType.FullName] = strKey;
}
return strKey;
}
}
}
五、运行测试
新建一个控制台程序:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LinkTo.ORM.Model; namespace LinkTo.ORM.Client { class Program { static void Main() { //新增 Person insertPerson = new Person { Name = "Hello", Age = 18, Gender = "male" }; int insertResult = DBHelper.Insert(insertPerson); Console.WriteLine($"共新增了 {insertResult} 条记录。"); //更新 List<Person> updateList = DBHelper.Query<Person>("Name='Hello'"); int updateResult = 0; if (updateList.Count > 0) { foreach (var item in updateList) { Person updatePerson = item; updatePerson.Age = 19; updateResult += DBHelper.Update(updatePerson); } } Console.WriteLine($"共更新了 {updateResult} 条记录。"); //查询 List<Person> selectList = DBHelper.Query<Person>("Name='Hello'"); if (selectList.Count > 0) { foreach (var item in selectList) { Console.WriteLine("person.Name = " + item.Name); Console.WriteLine("person.Age = " + item.Age); Console.WriteLine("person.Gender = " + item.Gender); } } //删除 int deleteResult = DBHelper.Delete<Person>("Name='Hello'"); Console.WriteLine($"共删除了 {deleteResult} 条记录。"); Console.Read(); } } }
运行结果如下:
源码下载