热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

EntityFramework系列:SQLite的CodeFrist和RowVersion

没什么好说的,能支持DropCreateDatabaseIfModelChanges和RowVersion的Sqlite谁都想要。EntityFramework7正在添加对Sqli

没什么好说的,能支持DropCreateDatabaseIfModelChangesRowVersion的Sqlite谁都想要。EntityFramework7正在添加对Sqlite的支持,虽然EF7不知道猴年马月才能完成正式版,更不知道MySql等第三方提供程序会在什么时候跟进支持,但是EF7中的确出现了Sqlite的相关代码。Sqlite支持EF6的CodeFirst,只是不支持从实体生成数据库,估计有很多人因为这个原因放弃了使用它。现在SQLite.CodeFirst的简单实现可以让我们生成数据库,因此在等待EF7的可以预见的长时间等待中,我们可以使用SQLite.CodeFirst,毕竟我们只是开发的时候使用DropCreateDatabaseIfModelChanges,Release时不会使用更不用担心SQLite.CodeFirst的简单实现会带来什么问题。可以直接修改源码,也可以参考最后面通过反射实现自定义DropCreateDatabaseIfModelChanges的方式。

1.RowVersion的支持:

可以从我的上一篇:在MySql中使用和SqlServer一致的RowVersion并发控制中采用相同的策略即可。我已经测试过在Sqlite中的可行性。

1.首先是RowVersion的配置:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove
();
modelBuilder.Configurations.AddFromAssembly(
typeof(SqliteDbContext).Assembly);
modelBuilder.Properties()
.Where(o
=> o.Name == "RowVersion")
.Configure(o
=> o.IsConcurrencyToken()
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None));
Database.SetInitializer(
new SqliteDbInitializer(Database.Connection.ConnectionString, modelBuilder));
}

2.然后是SaveChanges的重写:

public override int SaveChanges()
{
this.ChangeTracker.DetectChanges();
var objectCOntext= ((IObjectContextAdapter)this).ObjectContext;
foreach (ObjectStateEntry entry in objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Modified | EntityState.Added))
{
var v = entry.Entity as IRowVersion;
if (v != null)
{
v.RowVersion
= System.Text.Encoding.UTF8.GetBytes(Guid.NewGuid().ToString());
}
}
return base.SaveChanges();
}

3.生成__MigrationHistory:

DropCreateDatabaseIfModelChanges则需要修改SQLite.CodeFirst的代码,SQLite.CodeFirst生成的数据库不包含__MigrationHistory信息,所以我们首先修改SqliteInitializerBase添加__MigrationHistory,__MigrationHistory表是通过HistoryRow实体的映射,我们直接在EF源代码中找到相关部分作为参考。修改SqliteInitializerBase的SqliteInitializerBase方法,配置HistoryRow实体的映射。

public const string DefaultTableName = "__MigrationHistory";
internal const int COntextKeyMaxLength= 300;
internal const int MigratiOnIdMaxLength= 150;
protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder)
{
DatabaseFilePath
= SqliteConnectionStringParser.GetDataSource(connectionString);
ModelBuilder
= modelBuilder;
// This convention will crash the SQLite Provider before "InitializeDatabase" gets called.
// See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details.
modelBuilder.Conventions.Remove();
modelBuilder.Entity
().ToTable(DefaultTableName);
modelBuilder.Entity
().HasKey(
h
=> new
{
h.MigrationId,
h.ContextKey
});
modelBuilder.Entity
().Property(h => h.MigrationId).HasMaxLength(MigrationIdMaxLength).IsRequired();
modelBuilder.Entity
().Property(h => h.ContextKey).HasMaxLength(ContextKeyMaxLength).IsRequired();
modelBuilder.Entity
().Property(h => h.Model).IsRequired().IsMaxLength();
modelBuilder.Entity
().Property(h => h.ProductVersion).HasMaxLength(32).IsRequired();
}

4.初始化__MigrationHistory:

继续修改InitializeDatabase方法,在创建数据库后,初始化__MigrationHistory的信息。虽然采用了HistoryRow,但初始化信息我们只简单的使用生成的SQL语句作为判定实体和配置是否改变的依据,因为后面的InitializeDatabase方法中也是我们自己来判定实体和配置是否改变。

public virtual void InitializeDatabase(TContext context)
{
var model = ModelBuilder.Build(context.Database.Connection);
using (var transaction = context.Database.BeginTransaction())
{
try
{
var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model);
sqliteDatabaseCreator.Create();
/*start*/
context.Set
().Add(
new HistoryRow
{
MigrationId
= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff"),
ContextKey
= context.GetType().FullName,
Model
= System.Text.Encoding.UTF8.GetBytes(sqliteDatabaseCreator.GetSql().ToCharArray()),
ProductVersion
= "6.1.2"
});
/*end*/
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
using (var transaction = context.Database.BeginTransaction())
{
try
{
Seed(context);
context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}

5.添加DropCreateDatabaseIfModelChanges支持

添加SqliteDropCreateDatabaseIfModelChanges类,在InitializeDatabase方法中判读实体和配置是否改变。需要注意的是,删除sqlite文件时,即使关闭Connection和调用GC.Collect()仍然在第一次无法删除文件,所以必须进行多次尝试。

public override void InitializeDatabase(TContext context)
{
bool dbExists = File.Exists(DatabaseFilePath);
if (dbExists)
{
var model = ModelBuilder.Build(context.Database.Connection);
var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model);
var newSql = sqliteDatabaseCreator.GetSql();
var oldSql = "";
oldSql
= System.Text.Encoding.UTF8.GetString(context.Set().AsNoTracking().FirstOrDefault().Model);
context.Database.Connection.Close();
GC.Collect();
if (oldSql == newSql)
{
return;
}
for (int i = 0; i <10; i++)
{
try
{
File.Delete(DatabaseFilePath);
break;
}
catch (Exception)
{
System.Threading.Thread.Sleep(
1);
}
}
}
base.InitializeDatabase(context);
}

 

核心的代码已经贴出来,SQLite.CodeFirst本身的实现就比较简易,我添加的代码也比较简陋,因此在代码上没什么参考价值,只有使用和实用价值。毕竟只是在Debug开发时才需要这些功能的支持,对Sqlite本身和EF的提供程序没有任何影响。到这里终于松了口气,我们现在可以使用:Sql Server(CE)、Sqlite和Mysql进行Code First开发,采用相同的实体定义和配置,并且采用相同的并发控制。非Sql Server(CE)的并发控制和Sqlite不支持从代码生成数据库这两点终于克服了。

6.不修改源代码,使用反射实现

修改源码是由于SQLite.CodeFirst的内部类无法调用,考虑到可以使用反射,于是有了下面不需要修改源码,通过反射实现直接自定义DropCreateDatabaseIfModelChanges的方式:

《EntityFramework系列:SQLite的CodeFrist和RowVersion》
《EntityFramework系列:SQLite的CodeFrist和RowVersion》

using SQLite.CodeFirst.Statement;
using System;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations.History;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.IO;
using System.Linq;
using System.Reflection;
namespace SQLite.CodeFirst
{
public class SqliteDropCreateDatabaseIfModelChanges : IDatabaseInitializer where TContext : DbContext
{
protected readonly DbModelBuilder ModelBuilder;
protected readonly string DatabaseFilePath;
public const string DefaultTableName = "__MigrationHistory";
private const string DataDirectoryToken = "|datadirectory|";
internal const int COntextKeyMaxLength= 300;
internal const int MigratiOnIdMaxLength= 150;
public SqliteDropCreateDatabaseIfModelChanges(string connectionString, DbModelBuilder modelBuilder)
{
DatabaseFilePath
= ConnectionStringParse(connectionString);
ModelBuilder
= modelBuilder;
// This convention will crash the SQLite Provider before "InitializeDatabase" gets called.
// See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details.
modelBuilder.Conventions.Remove();
ConfigMigrationHistory(modelBuilder);
}
private string ConnectionStringParse(string connectionString)
{
var path = connectionString.Trim(' ', ';').Split(';').FirstOrDefault(o => o.StartsWith("data source", StringComparison.OrdinalIgnoreCase)).Split('=').Last().Trim();
if (!path.StartsWith("|datadirectory|", StringComparison.OrdinalIgnoreCase))
{
return path;
}
string fullPath;
// find the replacement path
object rootFolderObject = AppDomain.CurrentDomain.GetData("DataDirectory");
string rootFolderPath = (rootFolderObject as string);
if (rootFolderObject != null && rootFolderPath == null)
{
throw new InvalidOperationException("The value stored in the AppDomains 'DataDirectory' variable has to be a string!");
}
if (string.IsNullOrEmpty(rootFolderPath))
{
rootFolderPath
= AppDomain.CurrentDomain.BaseDirectory;
}
// We don't know if rootFolderpath ends with '\', and we don't know if the given name starts with onw
int fileNamePosition = DataDirectoryToken.Length; // filename starts right after the '|datadirectory|' keyword
bool rootFolderEndsWith = (0 1] == '\\';
bool fileNameStartsWith = (fileNamePosition '\\';
// replace |datadirectory| with root folder path
if (!rootFolderEndsWith && !fileNameStartsWith)
{
// need to insert '\'
fullPath = rootFolderPath + '\\' + path.Substring(fileNamePosition);
}
else if (rootFolderEndsWith && fileNameStartsWith)
{
// need to strip one out
fullPath = rootFolderPath + path.Substring(fileNamePosition + 1);
}
else
{
// simply concatenate the strings
fullPath = rootFolderPath + path.Substring(fileNamePosition);
}
return fullPath;
}
private void ConfigMigrationHistory(DbModelBuilder modelBuilder)
{
modelBuilder.Entity
().ToTable(DefaultTableName);
modelBuilder.Entity
().HasKey(
h
=> new
{
h.MigrationId,
h.ContextKey
});
modelBuilder.Entity
().Property(h => h.MigrationId).HasMaxLength(MigrationIdMaxLength).IsRequired();
modelBuilder.Entity
().Property(h => h.ContextKey).HasMaxLength(ContextKeyMaxLength).IsRequired();
modelBuilder.Entity
().Property(h => h.Model).IsRequired().IsMaxLength();
modelBuilder.Entity
().Property(h => h.ProductVersion).HasMaxLength(32).IsRequired();
}
public string GetSql(DbModel model)
{
Assembly asm
= Assembly.GetAssembly(typeof(SqliteInitializerBase<>));
Type builderType
= asm.GetType("SQLite.CodeFirst.Builder.CreateDatabaseStatementBuilder");
ConstructorInfo builderConstructor
= builderType.GetConstructor(new Type[] { typeof(EdmModel) });
Object builder
= builderConstructor.Invoke(new Object[] { model.StoreModel });
MethodInfo method
= builderType.GetMethod("BuildStatement", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.Public);
var statement = (IStatement)method.Invoke(builder, new Object[] { });
string sql = statement.CreateStatement();
return sql;
}
public void InitializeDatabase(TContext context)
{
var model = ModelBuilder.Build(context.Database.Connection);
var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model);
var newSql = this.GetSql(model);
bool dbExists = File.Exists(DatabaseFilePath);
if (dbExists)
{
var oldSql = System.Text.Encoding.UTF8.GetString(context.Set().AsNoTracking().FirstOrDefault().Model);
context.Database.Connection.Close();
GC.Collect();
if (oldSql == newSql)
{
return;
}
for (int i = 0; i <10; i++)
{
try
{
File.Delete(DatabaseFilePath);
break;
}
catch (Exception)
{
System.Threading.Thread.Sleep(
1);
}
}
}
using (var transaction = context.Database.BeginTransaction())
{
try
{
sqliteDatabaseCreator.Create();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
using (var transaction = context.Database.BeginTransaction())
{
try
{
context.Set
().Add(
new HistoryRow
{
MigrationId
= DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff"),
ContextKey
= context.GetType().FullName,
Model
= System.Text.Encoding.UTF8.GetBytes(newSql.ToCharArray()),
ProductVersion
= "6.1.3"
});
Seed(context);
context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
protected virtual void Seed(TContext context)
{
}
}
}

View Code

 

希望你不是找了好久才找到这个解决方案。


推荐阅读
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • 本文介绍了如何使用php限制数据库插入的条数并显示每次插入数据库之间的数据数目,以及避免重复提交的方法。同时还介绍了如何限制某一个数据库用户的并发连接数,以及设置数据库的连接数和连接超时时间的方法。最后提供了一些关于浏览器在线用户数和数据库连接数量比例的参考值。 ... [详细]
  • Nginx使用AWStats日志分析的步骤及注意事项
    本文介绍了在Centos7操作系统上使用Nginx和AWStats进行日志分析的步骤和注意事项。通过AWStats可以统计网站的访问量、IP地址、操作系统、浏览器等信息,并提供精确到每月、每日、每小时的数据。在部署AWStats之前需要确认服务器上已经安装了Perl环境,并进行DNS解析。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • Linux服务器密码过期策略、登录次数限制、私钥登录等配置方法
    本文介绍了在Linux服务器上进行密码过期策略、登录次数限制、私钥登录等配置的方法。通过修改配置文件中的参数,可以设置密码的有效期、最小间隔时间、最小长度,并在密码过期前进行提示。同时还介绍了如何进行公钥登录和修改默认账户用户名的操作。详细步骤和注意事项可参考本文内容。 ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 本文介绍了PhysioNet网站提供的生理信号处理工具箱WFDB Toolbox for Matlab的安装和使用方法。通过下载并添加到Matlab路径中或直接在Matlab中输入相关内容,即可完成安装。该工具箱提供了一系列函数,可以方便地处理生理信号数据。详细的安装和使用方法可以参考本文内容。 ... [详细]
  • 图解redis的持久化存储机制RDB和AOF的原理和优缺点
    本文通过图解的方式介绍了redis的持久化存储机制RDB和AOF的原理和优缺点。RDB是将redis内存中的数据保存为快照文件,恢复速度较快但不支持拉链式快照。AOF是将操作日志保存到磁盘,实时存储数据但恢复速度较慢。文章详细分析了两种机制的优缺点,帮助读者更好地理解redis的持久化存储策略。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 本文介绍了Web学习历程记录中关于Tomcat的基本概念和配置。首先解释了Web静态Web资源和动态Web资源的概念,以及C/S架构和B/S架构的区别。然后介绍了常见的Web服务器,包括Weblogic、WebSphere和Tomcat。接着详细讲解了Tomcat的虚拟主机、web应用和虚拟路径映射的概念和配置过程。最后简要介绍了http协议的作用。本文内容详实,适合初学者了解Tomcat的基础知识。 ... [详细]
  • 原文地址:https:www.cnblogs.combaoyipSpringBoot_YML.html1.在springboot中,有两种配置文件,一种 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 本文介绍了Oracle数据库中tnsnames.ora文件的作用和配置方法。tnsnames.ora文件在数据库启动过程中会被读取,用于解析LOCAL_LISTENER,并且与侦听无关。文章还提供了配置LOCAL_LISTENER和1522端口的示例,并展示了listener.ora文件的内容。 ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
author-avatar
湖南美景创意动画设计有限公司
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有