vendredi 14 août 2015

c# sqlite.net NotSupportedException or InvalidCastException

I am working on a windows universal app and use SQLite including the corresponding SQLite.cs and SQLiteAsync.cs from nuget.

I got the implementation idea from this MVA course

Problem

When I call myModelRepositoryInstance.LoadAllAsync() I don't get any errors.
When I call myModelRepositoryInstance.LoadByIdAsync(guid) I get an

InvalidCastException ("Object must implement IConvertible")

When I omit the 'class' constraint in the classes IRepository.cs and RepositoryBase.cs, I get

NotSupportedException ("Cannot compile: Parameter")

This is what I got first and with the help of another SO Q&A I added the class constraint.

My code is as follows:

IKeyedTable.cs

public interface IKeyedTable<K>{  
    [PrimaryKey]  
    K Id{get; set;}
}  

MyModelBase.cs

public class MyModelBase<K> : IKeyedTable<K>{
    public abstract K Id{get; set;}
}

MyModel.cs

public class MyModel : MyModelBase<MyModel, Guid>{
    [PrimaryKey, Column("Id")]
    public override Guid Id { 
        get { return GetProperty<Guid>(); } 
        set { SetProperty(value); } 
    }
}

IRepository.cs

public interface IRepository<T, K> where T : class, IKeyedTable<K>, new()
{
    Task<T> LoadByIdAsync(K id);
    Task<IEnumerable<T>> LoadAllAsync();
    Task InsertAsync(T item);
    Task UpdateAsync(T item);
    Task DeleteAsync(T item);
    AsyncTableQuery<T> Query();
}

RepositoryBase.cs

public abstract class RepositoryBase<TTable, K> : IRepository<TTable, K> where TTable :  class, IKeyedTable<K>, new()
{
    protected ISQLiteService _SQLiteService;

    public RepositoryBase(ISQLiteService SQLiteService)
    {
        _SQLiteService= SQLiteService;
    }

    public async Task<TTable> LoadByIdAsync(K id)
    {
        var query = _SQLiteService.Connection.Table<TTable>().Where(item => item.Id.Equals(id));
        return await query.FirstOrDefaultAsync();
    }

    public async Task<IEnumerable<TTable>> LoadAllAsync()
    {
        var query = _SQLiteService.Connection.Table<TTable>();
        var array = (await query.ToListAsync()).ToArray();
        return array;
    }

    public Task InsertAsync(TTable item)
    {
        return _SQLiteService.Connection.InsertAsync(item);
    }

    public Task UpdateAsync(TTable item)
    {
        return _SQLiteService.Connection.UpdateAsync(item);
    }

    public Task DeleteAsync(TTable item)
    {
        return _SQLiteService.Connection.DeleteAsync(item);
    }

    public AsyncTableQuery<TTable> Query()
    {
        return _SQLiteService.Connection.Table<TTable>();
    }
}

MyModelRepository.cs

public class MyModelRepository : RepositoryBase<MyModel, Guid>{}

How would I get that to work?

Aucun commentaire:

Enregistrer un commentaire