C#基于DBContext(EF)实现通用增删改查的REST方法实例
作者:shichen2014 时间:2021-06-23 20:56:07
本文实例讲述了C#基于DBContext(EF)实现通用增删改查的REST方法,分享给大家供大家参考。具体如下:
我们用ADO.NET Entity Data Model来生成实体类后,一般都会对这些类进行基本的增删改查操作,如果每个类都要写这些基本的方法,实在太乏味了。下面就是通过step by step的方式介绍如何用DBContext来实现通用增删改查的REST方法,以及实现过程中容易出现的问题。
1. 打开vs2012,新建一个class library的项目
2. 新加一个ADO.NET Entity Data Model项到这个项目
3. 打开App.Config, 修改res://* 为res://yourproject
否则会报下面的这咱错误:
WIFI.ssdl(3,4) : error 0019: Each type name in a schema must be unique. Type name 'WifiModel.Store.AD' was already defined.
4. Build这个项目
5. 新建另一个web api的项目
ASP.NET MVC 4 Web Application –> Web API 模板
注意这个项目的EF的版本与上个项目的版本要一致
6. 添加一个类到Models下:
public class GenericDBContext<T> : WifiEntities where T : class
{
public DbSet<T> Items { get; set; }
public List<T> Get()
{
return Set<T>().ToList();
}
public T Get(int id)
{
return Items.Find(id);
}
public void Put(T item)
{
Items.Attach(item);
Entry(item).State = EntityState.Modified;
SaveChanges();
}
public void Post(T item)
{
Items.Add(item);
SaveChanges();
}
public void Delete(int id)
{
Delete(Get(id));
}
public void Delete(T item)
{
Items.Attach(item);
Entry(item).State = EntityState.Deleted;
SaveChanges();
}
}
7. 添加一个到Controllers下面:
public class GenericController<T> : ApiController where T : class
{
private readonly GenericDBContext<T> _context = new GenericDBContext<T>();
public List<T> Get()
{
return _context.Get();
}
public T Get(int id)
{
return _context.Get(id);
}
public void Post([FromBody]T t)
{
_context.Post(t);
}
public void Put([FromBody]T t)
{
_context.Put(t);
}
public void Delete(int id)
{
_context.Delete(id);
}
}
至此,通用方法写完了
8. 下面就可以写具体Controller了
public class ADController : GenericController<AD>
{
}
9. 最后用soap ui 进行调试,通过
希望本文所述对大家的C#程序设计有所帮助。
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
解决Spring在Thread中注入Bean无效的问题
SpringBoot自动配置原理详解
![](https://img.aspxhome.com/file/2023/6/58096_0s.jpg)
Flutter利用Hero组件实现自定义路径效果的动画
![](https://img.aspxhome.com/file/2023/3/85453_0s.png)
JDBC实现学生管理系统
MyBatis3源码解析之如何获取数据源详解
![](https://img.aspxhome.com/file/2023/3/60903_0s.jpg)
浅谈Java之Map 按值排序 (Map sort by value)
Spring Utils工具类常用方法实例
spring整合redis缓存并以注解(@Cacheable、@CachePut、@CacheEvict)形式使用
java为何不能多继承的原因详解
Java实现分页代码
MyBatis超详细讲解如何实现分页功能
![](https://img.aspxhome.com/file/2023/6/58216_0s.png)
Java线程池高频面试题总结
Java请求转发和请求重定向区别详解
![](https://img.aspxhome.com/file/2023/6/63786_0s.webp)
SpringBoot+netty-socketio实现服务器端消息推送
Spring Security前后分离校验token的实现方法
![](https://img.aspxhome.com/file/2023/5/60665_0s.png)
详细聊聊SpringBoot中动态切换数据源的方法
![](https://img.aspxhome.com/file/2023/9/59879_0s.png)
Idea如何导入一个SpringBoot项目的方法(图文教程)
![](https://img.aspxhome.com/file/2023/8/79208_0s.png)
ReentrantLock源码详解--条件锁
![](https://img.aspxhome.com/file/2023/8/69108_0s.png)