如何在C#中继承System.Data.SQLite

3

我使用System.Data.SQLite和C#来访问SQLite数据库/表。出于懒惰和快速开发的原因,我创建了自己的类库,将一些System.Data.SQLite方法封装在一个方法中,并创建了许多常见的数据库例程(方法),使我在访问数据时能够减少工作量。

如果我继承System.Data.SQLite库而不是引用它,是否可以帮助我优化我的工作?请给一个例子,谢谢。

2个回答

1

可以从SQLite继承并对一些类进行添加,特别是SQLiteConnection。但是,您无法在SQLite内部创建许多类(如SQLiteCommand和SQLiteParameter),因此无法告诉SQLite使用您的自定义版本。虽然有一个SQLiteFactory,但它用于ADO.NET数据提供程序集成,而不是由SQLite内部使用。

最好将您的方法保持独立。如果您希望它们感觉像库的一部分,可以使用扩展方法


0

这是一个很好的问题,7年后我没有找到太多答案!我刚刚做了一个简单的继承,发现有点棘手(因为我不完全熟悉约束泛型类型)。但这就是我最终使用的方法。

using SQLite; // Here using sqlite-net-pcl
using System.Collections.Generic;

namespace SQLiteEx
{
  class SQLiteConnection : SQLite.SQLiteConnection
  {
    // Must provide a constructor with at least 1 argument
    public SQLiteConnection(string path)
      : base(path)
    {
    }

    // With this class, you can automatically append 
    // some kind of global filter like LIMIT 1000 
    string mGlobalFilter = "";
    public string GlobalFilter
    {
      set { mGlobalFilter = value; }
      get { return string.IsNullOrWhiteSpace(mGlobalFilter) ? "" : " " + mGlobalFilter; }
    }

    // You MUST constrain the generic type with "where T : new()"
    // OTHERWISE feel the wrath of:
    // ===================================================================
    //  'T' must be a non-abstract type with a public parameterless 
    //  constructor in order to use it as parameter 'T' in the generic 
    //  type or method 'SQLiteConnection.Query<T>(string, params object[])'
    // ===================================================================
    public List<T> Query<T>(string sql) where T : new()
    {
      return base.Query<T>(sql + GlobalFilter);
    }
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接