[C#开发] SQLite with Entity Framework Code First

Entity Framework Code First默认使用SQL Server,这里提供使用SQLite的方法。

Prerequisites

支持NuGet和Entity Framework Code First的Visual Studio。

Steps

  1. 新建工程,在Solution Explorer里右键工程,选Manage NuGet Packages
  2. 找到System.Data.SQLite并安装。
  3. 参考Entity Framework Code First,新建一个Context(如UserContext),然后在.config(如Web.config)中加入连接字符串连接数据库mydb.db
  <connectionStrings>
    <add name="UserContext" connectionString="Data Source=|DataDirectory|mydb.db" providerName="System.Data.SQLite.EF6" />
  </connectionStrings>

同时修改(不加入System.Data.SQLite会出错,参考http://www.codeproject.com/Questions/731487/No-Entity-Framework-provider-found-for-the-ADO-NET

    <DbProviderFactories>
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider" invariant="System.Data.SQLite.EF6" description=".Net Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
      <remove invariant="System.Data.SQLite.EF6" />
      <add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
      <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" />
    </DbProviderFactories>

这样理论上就能通过DbContext以及DbSet等Entity Framework Code First的操作了。

Option

  • 新建SQLiteDbHelper在程序开始运行时自动新建数据库并建立相关的table。如以下示例:
using System.Data.SQLite;

namespace Test
{
    public class SQLiteDbHelper
    {
        public const string TABLE_USERS = "Users";

        private SQLiteConnection connection;

        /// <summary>
        /// Init SQLite DB connectionString.
        /// </summary>
        /// <param name="dbFilePath">SQLite Database file path</param>
        public SQLiteDbHelper(string dbFilePath)
        {
            string connectionString = "Data Source=" + dbFilePath;
            connection = new SQLiteConnection(connectionString);
        }

        /// <summary>
        /// Create DB and tables.
        /// </summary>
        public void Create()
        {
            connection.Open();
            SQLiteCommand command = connection.CreateCommand();
            command.CommandText = string.Format("CREATE TABLE {0}({1}, {2}, {3}, {4})",
                TABLE_USERS, "_id INTEGER PRIMARY KEY AUTOINCREMENT",
                "Name VARCHAR", "Email VARCHAR", "Password VARCHAR");
            command.ExecuteNonQuery();
            connection.Close();
        }
    }

        /// <summary>
        /// Executes a Transact-SQL statement against the connection and returns the number
        /// of rows affected.
        /// </summary>
        /// <param name="sql">sql command</param>
        /// <param name="parameters">The parameters of sql command.</param>
        /// <returns>The number of rows affected.</returns>
        public int ExecuteNonQuery(string sql, SQLiteParameter[] parameters)
        {
            int affectedRows = 0;
            connection.Open();
            using (DbTransaction transaction = connection.BeginTransaction())
            {
                using (SQLiteCommand command = new SQLiteCommand(sql, connection))
                {
                    if (parameters != null)
                    {
                        command.Parameters.AddRange(parameters);
                    }
                    affectedRows = command.ExecuteNonQuery();
                }
                transaction.Commit();
            }
            connection.Close();
            return affectedRows;
        }

        /// <summary>
        /// Sends the command to the connection and builds a SQLiteDataReader.
        /// </summary>
        /// <param name="sql">sql command</param>
        /// <param name="parameters">The parameters of sql command.</param>
        /// <returns>A SQLiteDataReader object.</returns>
        public SQLiteDataReader ExecuteReader(string sql, SQLiteParameter[] parameters)
        {
            SQLiteCommand command = new SQLiteCommand(sql, connection);
            if (parameters != null)
            {
                command.Parameters.AddRange(parameters);
            }
            connection.Open();
            return command.ExecuteReader(CommandBehavior.CloseConnection);
        }

        /// <summary>
        /// Executes the query, and returns the first column of the first row in the result
        /// set returned by the query. Additional columns or rows are ignored.
        /// </summary>
        /// <param name="sql">sql command</param>
        /// <param name="parameters">The parameters of sql command.</param>
        /// <returns>The first column of the first row in the result set, or a null reference
        /// if the result set is empty. Returns a maximum of 2033 characters.</returns>
        public Object ExecuteScalar(string sql, SQLiteParameter[] parameters)
        {
            using (SQLiteCommand command = new SQLiteCommand(sql, connection))
            {
                if (parameters != null)
                {
                    command.Parameters.AddRange(parameters);
                }
                SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                return dataTable;
            }
        }
    }
}
  • 初始化DB
// Init DB.
string dbFilePath = Path.Combine(AppDomain.CurrentDomain.GetData("DataDirectory").ToString(), "mydb.db");
SQLiteDbHelper sqliteDbHelper = new SQLiteDbHelper(dbFilePath);
if (!File.Exists(dbFilePath))
{
    sqliteDbHelper.Create();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
NetCore SQLite CodeFirst 是使用 NetCore 框架来创建和管理 SQLite 数据库的一种方法。CodeFirst 是一种数据库开发模式,它能够根据实体类的结构自动创建数据库表和字段,并在运行时生成必要的 SQL 语句来操作数据库。 在使用 NetCore SQLite CodeFirst 之前,首先需要安装 Entity Framework Core 的 SQLite 提供程序。可以通过 NuGet 包管理器或者命令行工具来安装。 安装完成后,可以通过定义实体类来创建数据库表。在实体类中,可以使用 Data Annotations 或者 Fluent API 来定义各个属性的映射关系。比如可以使用 [Table]、[Key]、[Column] 等属性来定义表名、主键和字段名等。 在程序启动时,可以添加启动配置来调用 DbContext 来生成数据库。通过继承 DbContext 并覆盖 OnConfiguring 方法,可以设置数据库连接字符串、数据表生成策略等配置项。 然后,可以通过调用 DbContext 的 SaveChanges 方法来将实体类的数据持久化到数据库中。当需要添加、删除或修改数据时,只需对实体类做相应的操作,并调用 SaveChanges 方法即可。 另外,NetCore SQLite CodeFirst 还支持迁移功能,即可以通过命令行工具生成数据库迁移脚本,从而实现数据库结构的版本控制和更新。 综上所述,NetCore SQLite CodeFirst 提供了一种方便快捷的方式来创建和管理 SQLite 数据库,能够根据实体类的结构自动生成数据库表和字段,同时还支持迁移功能,方便进行数据库结构的版本控制和更新。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值