TNBLOG
首页
博客
视频
资源
问答
猿趣
手机
关于
搜索
收藏
便签
笔记
消息
创作
登录
剑轩
故如虹,知恩;故如月,知明
博主信息
排名
6
文章
6
粉丝
16
评论
8
文章类别
CSS
15篇
微服务
41篇
Git
14篇
.NET
102篇
移动开发
33篇
软件架构
23篇
.NET Core
118篇
.NET MVC
11篇
英语
3篇
随笔
86篇
Bootstrap
3篇
Redis
21篇
编辑器
10篇
Js相关
15篇
虚拟化
8篇
更多
Oracle
7篇
Python
14篇
数据库
26篇
EF
17篇
微信
3篇
前端
151篇
消息队列
6篇
docker
41篇
多线程
1篇
Java
4篇
软件基础
2篇
C++
2篇
WCF
7篇
Linux
7篇
nginx
5篇
K8S
9篇
ABP
2篇
最新文章
最新评价
{{item.articleTitle}}
{{item.blogName}}
:
{{item.content}}
关于我们
ICP备案 :
渝ICP备18016597号-1
网站信息:
2018-2024
TNBLOG.NET
技术交流:
群号656732739
联系我们:
contact@tnblog.net
欢迎加群
欢迎加群交流技术
原
ef core 公共接口封装
5954
人阅读
2019/10/11 17:21
总访问:
3842603
评论:
0
收藏:
0
手机
分类:
.NET Core
show me code: ``` public interface ICommonDAL<T> where T : class, new() { protected EFContext context { get; } /// <summary> /// 新增一个实体 /// </summary> /// <param name="entity"></param> /// <returns></returns> public int Add(T entity) { if (entity == null) return -1; context.Entry<T>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added; return context.SaveChanges(); } /// <summary> /// 批量添加 /// </summary> /// <param name="entitys"></param> /// <returns></returns> public int BatchAdd(List<T> entitys) { if (entitys == null) return -1; foreach (T item in entitys) { context.Entry<T>(item).State = Microsoft.EntityFrameworkCore.EntityState.Added; } return context.SaveChanges(); } public int Deleted(T entity) { if (entity == null) return -1; context.Entry<T>(entity).State = Microsoft.EntityFrameworkCore.EntityState.Deleted; return context.SaveChanges(); } public T AddReturnEntity(T entity) { context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added; int count = context.SaveChanges(); if (count > 0) return entity; else return null; } public int Update(T t, string keyName) { var entry = context.Entry<T>(t); //把user对象加入上下文,但是没有改变 entry.State = Microsoft.EntityFrameworkCore.EntityState.Unchanged; //使用反射找到不为空的字段 foreach (var item in t.GetType().GetProperties()) { //虚拟属性是导航属性 if (item.GetMethod.IsVirtual) { continue; } //拿到属性值 object obj = item.GetValue(t); if (obj != null) { //不是主键才去修改,如果是主键就不需要修改了 if (item.Name != keyName) { //表示该字段需要更新 entry.Property(item.Name).IsModified = true; } } } return context.SaveChanges(); } public T GetElementById(int Id) { string name = typeof(T).Name; T element = context.Database.SqlQuery<T>("select * from " + name + " where Id=@Id", new SqlParameter("@Id", Id)).FirstOrDefault(); return element; } //public T GetMyNoteFileById(int Id) //{ // T value = context.Set<T>().Where(a=>a.); // return myNoteFile; //} } ```
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
👈{{preArticle.title}}
👉{{nextArticle.title}}
评价
{{titleitem}}
{{titleitem}}
{{item.content}}
{{titleitem}}
{{titleitem}}
{{item.content}}