Entity Framework(二) 一 封装EF通用类
2017-12-05 17:16
4015 人阅读

通过 Entity Framework1 一 Power Tools使用讲解 可以很容易的操作数据库,实现数据库增、删、改、查
但是很明显不管是新增还是删除、修改都调用了 entities.SaveChanges() 方法,而且修改、删除的时候还需要标记状态。
这里就是将这些代码进行封装,简化代码
1.首先新建一个接口: IDataRepository.cs
public interface IDataRepository { T Update<T>(T entity) where T : class; T Insert<T>(T entity) where T : class; void Delete<T>(T entity) where T : class; }
接口很简单,只有数据库修改、新增、删除
2.建立EF通用类并继承上面接口
public class DbContextBase : DbContext, IDataRepository, IDisposable { public DbContextBase(string connectionString) { this.Database.Connection.ConnectionString = connectionString; this.Configuration.LazyLoadingEnabled = false; this.Configuration.ProxyCreationEnabled = false; } public T Update<T>(T entity) where T : class { var set = this.Set<T>(); set.Attach(entity); this.Entry<T>(entity).State = EntityState.Modified; this.SaveChanges(); return entity; } public T Insert<T>(T entity) where T : class { this.Set<T>().Add(entity); this.SaveChanges(); return entity; } public void Delete<T>(T entity) where T : class { this.Entry<T>(entity).State = EntityState.Deleted; this.SaveChanges(); } public override int SaveChanges() { var result = base.SaveChanges(); return result; } }
3.修改下类 EntityDBContext.cs
继承DbContextBase
public partial class EntityDBContext : DbContextBase
无参构造函数修改如下
public EntityDBContext() : base(System.Configuration.ConfigurationManager.ConnectionStrings["EntityDBContext"].ConnectionString) { }
下面来测试用法
EntityFramework上下文
var entities = new EntityDBContext();
新增
USER_INFO userInfo = new USER_INFO() { USERNAME = "mike", USER_PWD = "22222", STATUS_CODE = 0, REMARK = "EF测试" }; entities.Insert(userInfo);
修改
USER_INFO mInfo = entities.USER_INFO.Where(q => q.USERID == 1001).FirstOrDefault(); if (mInfo != null) { mInfo.USERNAME = "mike2"; entities.Update(mInfo); }
删除
//USERID是主键 USER_INFO dInfo = entities.USER_INFO.Where(q => q.USERID == 1001).FirstOrDefault(); entities.Delete(dInfo);
和博主交个朋友吧
