sqlite-net-extensions -- Create Table Async

736 views Asked by At

My problem is that I'm using the CreateTableAsync method and is always returning "0". I researched and saw that this return is a mistake.

I wanted to know what I'm doing wrong.

Class Service Table:

public class SqliteTable
{
    private readonly SqliteWrapper _sqliteWrapper;

    public SqliteTable()
    {
        _sqliteWrapper = new SqliteWrapper();
    }

    private async Task<bool> CheckIfExistTable<T>() where T : new()
    {
        var connection = _sqliteWrapper.OpenDatabase();
        try
        {
            var result = await connection.Table<T>().CountAsync();
            return result.Equals(0);
        }
        catch (Exception e)
        {
            Logs.Logs.Error($"Error get count table {typeof(T).Name}: {e.Message}");
            return false;
        }
    }

    public async void CreateTable<T>() where T : new()
    {
        var connection = _sqliteWrapper.OpenDatabase();

        if (await CheckIfExistTable<T>())
        {
            Logs.Logs.Info($"This table {typeof(T).Name} was created");
            return;
        }

        var createTableResult = await connection.CreateTableAsync<T>();
        var value = createTableResult.Results.Values.FirstOrDefault();

        if (value.Equals(1))
        {
            Logs.Logs.Info($"Create table {typeof(T).Name}");
        }
        else
        {
            throw new Exception($"Error create table {typeof(T).Name}");
        }
    }
}

I create a Class Model Login. which would be the object to create the database.

public class Login
{
    public Login()
    {
    }

    public Login(string user, string password)
    {
        User = user;
        Password = password;
    }

    public Login(int id, string user, string password)
    {
        Id = id;
        User = user;
        Password = password;
    }

    [PrimaryKey, AutoIncrement, Column("login_id")]
    public int Id { get; set; }

    [Unique, NotNull, Column("login_user")]
    public string User { get; set; }

    [NotNull, Column("login_password")] public string Password { get; set; }
}

I create Class CreateTableAsync. Which would be to intanciar the SqliteTable, to call the method CreateTable sending the object to create the database:

protected override void OnStart()
    {
        try
        {
            var sqliteTable = new SqliteTable();
            sqliteTable.CreateTable<Login>();
        }
        catch (Exception e)
        {
            Logs.Logs.Error($"Error init application: {e.Message}");
        }
    }

Can someone help me?

0

There are 0 answers