访问/创建/写入几个SQLite表(通用SQLiteHelper)

时间:2016-10-06 13:58:58

标签: c# android sqlite generics xamarin

我目前正在重新构建我的Xamarin应用程序,以便将一些数据保存到设备中。

我已经创建了我的表(14),连接类,现在我在使用DataAccess(Helper)类时遇到了一些麻烦。我不得不把它变成通用的,因为我们正在谈论它的14个表,并且所有的CRUD操作似乎都能正常工作。

但是“GetById”和“List”方法不起作用,因为它说我传递的泛型类型“T”必须是引用类型才能将它用作参数:

    public class DataAccessSQLite<T> : IDisposable{

    public SQLiteConnection connection;

    public DataAccessSQLite()
    {
        var config = DependencyService.Get<ISQLConfig>();
        connection = new SQLiteConnection(config.Platform, config.Database);
        connection.CreateTable<T>();
    }

    public void Insert(T model)
    {
        connection.Insert(model);
    }

    public void Delete(T model)
    {
        connection.Delete(model);
    }

    public void Update(T model)
    {
        connection.Update(model);
    }

    public T GetbyId(int id)
    {
        //HERE IS THE ERROR:
        return connection.Table<T>().FirstOrDefault(x => x.Id == id);
    }

    public List<T> ToList()
    { 
        //ALSO HERE
        return connection.Table<T>().OrderBy().ToList();
    }

    public void Dispose()
    {
        connection.Dispose();
    }
}

我正在考虑实现一个单例aproach来访问所有表,但不知道我会怎么做。

我知道我现在使用的通用aproach(T)无论如何都不会对GetById起作用,因为他无法通过传递“T”来知道会得到什么ID。所以我真正需要的是以其他方式做到这一点。

如何通过它访问所有表格,使这个类具有通用性?

ERROR I'MGETTING:类型'T'必须是引用类型才能在泛型类型或方法'SQLiteConnection.Table()' <中将其用作参数'T' / p>

更新:

使用其中T:class 解决了我遇到的错误,但我仍然无法通过传递“T”来从表中获取Id

1 个答案:

答案 0 :(得分:0)

通过阅读您的错误,您应该尝试:

public class DataAccessSQLite<T> : IDisposable
    where T : class

where T : class是一个通用约束,指定T是引用类型,并且它不能是值类型。

相关问题