1.安装EntityFramework.Extended 或者 Z.EntityFramework.Plus.EF6(推荐)
2.更改MyDBContext配置
namespace EntityFrameworkCore { [DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))] public class MyDBContext : DbContext { public MyDBContext() :base("name=Default") { //新增配置 Database.SetInitializer<MyDBContext>(null); } //新增配置(Z.EntityFramework.Plus.EF6不需要) protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema(""); base.OnModelCreating(modelBuilder); } public DbSet<User> User { set; get; } //................... } }
3.Global.asax中注册扩展
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace YFAPICommon { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); EfExtendedRegister(); } //注册扩展(Z.EntityFramework.Plus.EF6不需要) private void EfExtendedRegister() { var container = new EntityFramework.Container(); EntityFramework.Locator.RegisterDefaults(container); container.Register<EntityFramework.Batch.IBatchRunner>(() => new EntityFramework.Batch.MySqlBatchRunner()); EntityFramework.Locator.SetContainer(container); } } }
4.使用
//注:Delete和Update之后不用再dbContext.SaveChanges(); dbContext.User.Where(u => u.id == 1).Delete(); dbContext.User.Where(u => u.id == 1).Update(u=>new User { nickName="my name"});
//Z.EntityFramework.Plus.EF6 public object future() { //三个值在一次SQL查询中获得,提高查询效率 var query = dbContext.User.Future(); var datalist = query.ToList(); int count = query.Count(); var data = query.FirstOrDefault(); return new { datalist, count, data }; }
//FromCache QueryCacheManager.ExpireAll();//清空缓存 dbContext.User.FromCache().ToList();//从缓存读取
文档: