5

我正在尝试删除存储在 Sqlite 数据库中的类型的记录。它失败并显示以下消息:

"Cannot store type: MyNamespace.PanelLog"

我有以下方法来删除记录:

    public static int DeletePanelLog(int id)
    {
        return me.db.DeleteItem<PanelLog>(id);
    }

其中 DeleteItem 定义为:

    public int DeleteItem<T>(int id) where T : IBusinessEntity, new()
    {
        lock (locker) {
#if NETFX_CORE
            return Delete(new T() { ID = id });
#else
            return Delete<T> (new T () { ID = id });
#endif
        }
    }

PanelLog 定义为:

public class PanelLog : IBusinessEntity
{
    public PanelLog(){}

    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }

    public uint Sequence { get; set; }
    public DateTime Time { get; set; }
    public string Message { get; set; }
    public bool Alarm { get; set; }
}

以下是 SQLite 的调用堆栈:

    public int Delete<T>(object primaryKey)
    {
        var map = GetMapping(typeof(T));
        var pk = map.PK;
        if (pk == null)
        {
            throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK");
        }
        var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
        return Execute(q, primaryKey); // in this case, primaryKey is a PanelLog object
    }

    public int Execute(string query, params object[] args)
    {
        var cmd = CreateCommand(query, args);

        if (TimeExecution)
        {
            if (_sw == null)
            {
                _sw = new Stopwatch();
            }
            _sw.Reset();
            _sw.Start();
        }

        var r = cmd.ExecuteNonQuery();

        if (TimeExecution)
        {
            _sw.Stop();
            _elapsedMilliseconds += _sw.ElapsedMilliseconds;
            Debug.WriteLine(string.Format("Finished in {0} ms ({1:0.0} s total)", _sw.ElapsedMilliseconds, _elapsedMilliseconds / 1000.0));
        }

        return r;
    }

    public int ExecuteNonQuery()
    {
        if (_conn.Trace)
        {
            Debug.WriteLine("Executing: " + this);
        }

        var r = SQLite3.Result.OK;
        var stmt = Prepare();
        r = SQLite3.Step(stmt);
        Finalize(stmt);
        if (r == SQLite3.Result.Done)
        {
            int rowsAffected = SQLite3.Changes(_conn.Handle);
            return rowsAffected;
        }
        else if (r == SQLite3.Result.Error)
        {
            string msg = SQLite3.GetErrmsg(_conn.Handle);
            throw SQLiteException.New(r, msg);
        }
        else
        {
            throw SQLiteException.New(r, r.ToString());
        }
    }

    Sqlite3Statement Prepare()
    {
        var stmt = SQLite3.Prepare2(_conn.Handle, CommandText);
        BindAll(stmt);
        return stmt;
    }

    void BindAll(Sqlite3Statement stmt)
    {
        int nextIdx = 1;
        foreach (var b in _bindings)
        {
            if (b.Name != null)
            {
                b.Index = SQLite3.BindParameterIndex(stmt, b.Name);
            }
            else
            {
                b.Index = nextIdx++;
            }

            BindParameter(stmt, b.Index, b.Value, _conn.StoreDateTimeAsTicks);
        }
    }

执行在以下最后一行失败:(此处为第 1051 行

// line 1027 of http://code.google.com/p/sqlite-net/source/browse/trunk/src/SQLite.cs
internal static void BindParameter(Sqlite3Statement stmt, int index, object value, bool storeDateTimeAsTicks)
{
    if (value == null)
    {
        SQLite3.BindNull(stmt, index);
    }
    else
    {
        if (value is Int32)
        {
            SQLite3.BindInt(stmt, index, (int)value);
        }
        else if (value is String)
        {
            SQLite3.BindText(stmt, index, (string)value, -1, NegativePointer);
        }
        else if (value is Byte || value is UInt16 || value is SByte || value is Int16)
        {
            SQLite3.BindInt(stmt, index, Convert.ToInt32(value));
        }
        else if (value is Boolean)
        {
            SQLite3.BindInt(stmt, index, (bool)value ? 1 : 0);
        }
        else if (value is UInt32 || value is Int64)
        {
            SQLite3.BindInt64(stmt, index, Convert.ToInt64(value));
        }
        else if (value is Single || value is Double || value is Decimal)
        {
            SQLite3.BindDouble(stmt, index, Convert.ToDouble(value));
        }
        else if (value is DateTime)
        {
            if (storeDateTimeAsTicks)
            {
                SQLite3.BindInt64(stmt, index, ((DateTime)value).Ticks);
            }
            else
            {
                SQLite3.BindText(stmt, index, ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"), -1, NegativePointer);
            }
#if !NETFX_CORE
        }
        else if (value.GetType().IsEnum)
        {
#else
} else if (value.GetType().GetTypeInfo().IsEnum) {
#endif
            SQLite3.BindInt(stmt, index, Convert.ToInt32(value));
        }
        else if (value is byte[])
        {
            SQLite3.BindBlob(stmt, index, (byte[])value, ((byte[])value).Length, NegativePointer);
        }
        else if (value is Guid)
        {
            SQLite3.BindText(stmt, index, ((Guid)value).ToString(), 72, NegativePointer);
        }
        else
        {
            throw new NotSupportedException("Cannot store type: " + value.GetType());
        }
    }
}

它似乎试图绑定对象类型,而不是对象的值。这个对吗?我能做些什么来解决这个问题吗?

编辑:

经过一些进一步的测试,似乎以下工作:

    public int Delete(object objectToDelete)
    {
        var map = GetMapping(objectToDelete.GetType());
        var pk = map.PK;
        if (pk == null)
        {
            throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK");
        }
        var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
        return Execute(q, pk.GetValue(objectToDelete));
    }
4

2 回答 2

11

我也遇到了这个问题。实际上它来自DeleteItem定义内的一行:

return Delete<T> (new T () { ID = id });

它应该是:

return Delete<T> (id);
于 2013-10-25T18:30:27.287 回答
3

而不是使用:

   public int DeleteItem<T>(int id) where T : IBusinessEntity, new()
    {
        lock (locker) {
    #if NETFX_CORE
            return Delete(new T() { ID = id });
    #else
            return Delete<T> (new T () { ID = id });
    #endif
        }
    }

改用这个:

   public int Delete(object objectToDelete)
    {
        var map = GetMapping(objectToDelete.GetType());
        var pk = map.PK;
        if (pk == null)
        {
            throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK");
        }
        var q = string.Format("delete from \"{0}\" where \"{1}\" = ?", map.TableName, pk.Name);
        return Execute(q, pk.GetValue(objectToDelete));
    }
于 2013-08-15T08:50:05.080 回答