开发者

How to inherit System.Data.SQLite in C#

开发者 https://www.devze.com 2022-12-16 17:46 出处:网络
I use System.Data.SQLite and C# for accesing SQLite databases/tables. For lazy and fast development reasons, I created my own library of classes to encapsulate some of System.Data.SQLite methods in on

I use System.Data.SQLite and C# for accesing SQLite databases/tables. For lazy and fast development reasons, I created my own library of classes to encapsulate some of System.Data.SQLite methods in one method, and to create many common database routines (methods) that let me reduce my work when accessing to data.

If I would inherit System.Data.SQLite library instead of referencing it would help me to optimize my work, ¿is this possible? ¿may 开发者_运维技巧you give an example, please?


It's possible to inherit from SQLite and make additions to some of the classes, particularly SQLiteConnection. However, you won't be able to use your own classes everywhere as SQLite will internally create a lot of classes like SQLiteCommand and SQLiteParameter and you don't have an option to tell SQLite to use your custom versions. There is a SQLiteFactory, but this is used for ADO.NET data provider integration and is not used internally by SQLite.

You're much better off keeping your methods separate. If you want them to feel like they're part of the library you can use Extension Methods


This is a great question and I didn't find much in the way of answers 7-years later! I just had to do a simple inherit and found it a little tricky (because I wasn't completely familiar with constraining a generic type). But here's what I ended up with that worked.

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);
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消