EF+SQL server 转为 EF+SQLite

首先安装:sqlite-netFx40-setup-bundle-x86-2010-1.0.84.0.exe(http://system.data.sqlite.org/index.html/doc/trunk/www/downloads.wiki

http://www.sqlite.org/download.html)

然后把sql server中用到的数据库用sql server tosqlite db conveter.exe(http://www.hdxz.com/soft/zt000570.html)生成db后缀的数据文件放在某目录。

如果要查询可以用sqlitestudio.exe工具。

1.引用System.Data.SQLite.dll和System.Data.SQLite.Linq.dll

2.新建一个ADO.NET实体数据模型,也就edmx文件,新建过程和建sql server那个edmx文件一样,注意建立过程中“模型命名空间”改为和sql server那个edmx一样,建好后右键edmx文件以xml打开方式打开,

把节点edmx:StorageModels下的schema的provider改为System.Data.SQLite,然后把改emdx的后台代码中的#Entity部分删除,不然会有entity的重复定义。到这来EF的步骤就完成了

3.调用工程中

 配置文件添加

<system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite"/>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite, Version=1.0.57.0, Culture=neutral, PublicKeyToken=db937bc2d44ff139" />
    </DbProviderFactories>
  </system.data>

4.调用工程中新增ConnectionString

<add name="***_sqlite" connectionstring="metadata=res://*/Model.UserModel.csdl|res://*/ModelSqlite.ModelSqlite.ssdl|res://*/modelSqlite.ModelSqlite.msl;Provider=System.Data.SQLite;provider connection string='data source={0}'"/>

之前sql server 的connectionstring 是:<add name="***_sqlite" connectionstring="metadata=res://*/Model.UserModel.csdl|res://*/Model.UserModel.ssdl|res://*/Model.UserModel.msl;Provider=System.Data.SQLite;provider connection string='data source=.;initial catalog=usermangemnet;integrated security=true'"/>

两个对比也就说应用了sql server 那个edmx的csdl部分,然后 provider connection string 只需提供数据库db文件的路径就可以。到这里配置就完成了

5.接下来就是如何在两种数据库中切换了:可以利用“条件编译符号”

比如在某项目中的生成属性中定义条件编译符号有Test那么就可以在代码中切换两种数据库了

#if(Test)

this._eneties=new usermangementEntity(string.formate(***_sqlite+"db文件的路径"));

#else

this._ennties=new usermanagementEntiry(connectionstring);

#endif

猜你喜欢

转载自evencode.iteye.com/blog/1821723
EF