SQLite.net SQLiteFunction not working in Linq to SQL

前端 未结 1 2050
借酒劲吻你
借酒劲吻你 2020-12-14 03:56

I\'ve created a handful of custom SQLite functions in C# using System.Data.SQLite.SQLiteFunction. It works great when using SQLiteDataAdapter to execute queries, it

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 04:44

    Just that moment I found this nice snippet from this question

    // from https://stackoverflow.com/questions/172735/create-use-user-defined-functions-in-system-data-sqlite
    // taken from http://sqlite.phxsoftware.com/forums/p/348/1457.aspx#1457
    [SQLiteFunction(Name = "REGEXP", Arguments = 2, FuncType = FunctionType.Scalar)]
    public class RegExSQLiteFunction : SQLiteFunction {
        public override object Invoke(object[] args) {
            return System.Text.RegularExpressions.Regex.IsMatch(Convert.ToString(args[1]), Convert.ToString(args[0]));
        }
    }
    

    But didn't find how to use it. Now there's a SQLiteConnection.BindFunction method. It's ugly so I made a little extension method:

    public static void BindFunction(this SQLiteConnection connection, SQLiteFunction function) 
    {
        var attributes = function.GetType().GetCustomAttributes(typeof(SQLiteFunctionAttribute), true).Cast().ToArray();
        if (attributes.Length == 0) {
            throw new InvalidOperationException("SQLiteFunction doesn't have SQLiteFunctionAttribute");
        }
        connection.BindFunction(attributes[0], function);
    }
    

    And now you just have to

    using (var connection = new SQLiteConnection( "Data Source=YourDB.sqlite" )) 
    {
        connection.Open(); // Connection must be open to bind a function
    
        connection.BindFunction(new RegExSQLiteFunction());
    
        // Here create a command, and try REGEXP, for example
        // SELECT * FROM "table" WHERE "column" REGEXP '(?i)\btest\b'
        // looks for the word 'test', case-insensitive in a string column
    }
    

    Now how you can do it in LINQ to SQL, I don't exactly know because I've got my own SQL on LINQ IQueryProvider. This is how you can do it with the basic IDbConnection, IDbCommand, IDbDataParameter and IDataReader interfaces and your custom SQLiteFunction.

    0 讨论(0)
提交回复
热议问题