ef和mysql使用(二)--让mysql支持EntityFramework.Extended实现批量更新和删除

我们都知道Entity Framework 中不能同时更新多条记录,但是一个老外写的扩展库可以实现此功能EntityFramework.Extended,但是如何是mysql数据库要怎么实现呢

首先实现一个自定义类继承于MySqlEFConfiguration:

 public class MySqlDBconfiguration : MySqlEFConfiguration
    {
        public MySqlDBconfiguration()
        {
            SetExecutionStrategy(MySqlProviderInvariantName.ProviderName, () => new MySqlExecutionStrategy());
        } 
}

然后程序初始化的时候,修改ef执行环境:

 protected void Application_Start(object sender, EventArgs e)
        {
            EntityFramework.Locator.Current.Register<IBatchRunner>(() => new MySqlBatchRunner());
            DbConfiguration.SetConfiguration(new MySqlDBconfiguration());
        }

最后实现自定义的dbcontext:

 [DbConfigurationType(typeof(MySqlDBconfiguration))]
    public class TestContext : DbContext
    {
      private static TestContext _instance;

        public static TestContext Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new TestContext();
                }
                return _instance;
            }
        }
   private string _connectionString;

        public string ConnectionString
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    _connectionString = ConfigurationManager.ConnectionStrings["testConn"].ConnectionString;
                }
                return _connectionString;
            }
            set
            {
                _connectionString = value;
            }
        }

        public TestContext()
            : base("name=testConn")
        {
            _connectionString = ConfigurationManager.ConnectionStrings["testConn"].ConnectionString;
            Database.SetInitializer<TestContext>(null);//从不创建数据库,如果不加这句会报错=》An instance of 'MySqlDBconfiguration' was set but this type was not discovered in the same assembly as the 'MySqlHistoryContext' context
        }
        public TestContext(string connectionString)
            : base(connectionString)
        {

        }
        public DbSet<Person> Blogs { get; set; }
        public DbSet<DepartPerson> Posts { get; set; }
        protected override void OnModelCreating(DbModelBuilder 
        modelBuilder)
        {
           //如果没有下面这句,会采用mssql的默认schema=> dbo;所有想要使用mysql就应该加上下面这句。。或者再实体映射加上mysql数据库的schema;例如实体类DepartPerson=>特性[Table("DepartPerson", Schema= "test")]
            modelBuilder.HasDefaultSchema("");
            base.OnModelCreating(modelBuilder);
        }
    }

 具体使用方法:

 TestContext testContext = new TestContext();             
           var id = "1";
            testContext.Set<DepartPerson>().
                Where(c => c.ID == id).Delete();
            testContext.Set<DepartPerson>().
               Where(c => c.ID == id).Update(c => new DepartPerson { HospitalID = "0001" });

 

posted @ 2018-07-31 14:33  yaphetsfang  阅读(370)  评论(0编辑  收藏  举报