ef core 公共接口封装

 
  1. public interface ICommonDAL<T> where T : class, new()
  2. {
  3. protected EFContext context { get; }
  4. /// <summary>
  5. /// 新增一个实体
  6. /// </summary>
  7. /// <param name="entity"></param>
  8. /// <returns></returns>
  9. public int Add(T entity)
  10. {
  11. if (entity == null)
  12. return -1;
  13. context.Entry<T>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added;
  14. return context.SaveChanges();
  15. }
  16. /// <summary>
  17. /// 批量添加
  18. /// </summary>
  19. /// <param name="entitys"></param>
  20. /// <returns></returns>
  21. public int BatchAdd(List<T> entitys)
  22. {
  23. if (entitys == null)
  24. return -1;
  25. foreach (T item in entitys)
  26. {
  27. context.Entry<T>(item).State = Microsoft.EntityFrameworkCore.EntityState.Added;
  28. }
  29. return context.SaveChanges();
  30. }
  31. public int Deleted(T entity)
  32. {
  33. if (entity == null)
  34. return -1;
  35. context.Entry<T>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;
  36. return context.SaveChanges();
  37. }
  38. public T AddReturnEntity(T entity)
  39. {
  40. context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added;
  41. int count = context.SaveChanges();
  42. if (count > 0)
  43. return entity;
  44. else
  45. return null;
  46. }
  47. public int Update(T t, string keyName)
  48. {
  49. var entry = context.Entry<T>(t);
  50. //把user对象加入上下文,但是没有改变
  51. entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
  52. //使用反射找到不为空的字段
  53. foreach (var item in t.GetType().GetProperties())
  54. {
  55. //虚拟属性是导航属性
  56. if (item.GetMethod.IsVirtual)
  57. {
  58. continue;
  59. }
  60. //拿到属性值
  61. object obj = item.GetValue(t);
  62. if (obj != null)
  63. {
  64. //不是主键才去修改,如果是主键就不需要修改了
  65. if (item.Name != keyName)
  66. {
  67. //表示该字段需要更新
  68. entry.Property(item.Name).IsModified = true;
  69. }
  70. }
  71. }
  72. return context.SaveChanges();
  73. }
  74. public T GetElementById(int Id)
  75. {
  76. string name = typeof(T).Name;
  77. T element = context.Database.SqlQuery<T>("select * from " + name + " where Id=@Id", new SqlParameter("@Id", Id)).FirstOrDefault();
  78. return element;
  79. }
  80. //public T GetMyNoteFileById(int Id)
  81. //{
  82. // T value = context.Set<T>().Where(a=>a.);
  83. // return myNoteFile;
  84. //}
  85. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值