简体   繁体   中英

Why does select from sqlite db shows error 'Specified cast is not valid.' in Xamarin Forms?

Getting a single value from by SQLite database but I get the error System.InvalidCastException: 'Specified cast is not valid.' I need only the first value of the select results, tried both First() and ElementAtOrDefault(0) but same thing happens.

Error gets catched when trying to assing to the variable IDPromoMainPage, not before.

Basically this is how I call the value:

private void GetPromoLocal()
        {
            try
            {
                var databasePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "LocalDB.db3");
                var db = new SQLiteConnection(databasePath);
                IEnumerable<T_Promo> resultado = SELECT_WHERE(db);
                if (resultado.Count() > 0)
                {
                    IDPromoMainPage = Convert.ToInt32(resultado.First()); // ElementAtOrDefault(0));
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static IEnumerable<T_Promo> SELECT_WHERE(SQLiteConnection db)
        {
            return db.Query<T_Promo>("SELECT IDPromo FROM T_Promo");
        }

Also have the same error happening here, exactly at line "PisterosLista = resultado.Cast().ToList();"

List<Pisteros> PisterosLista = new List<Pisteros>();

public void GetPisterosLocal()
        {
            try
            {
                var databasePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "LocalDB.db3");
                var db = new SQLiteConnection(databasePath);
                IEnumerable<T_Pisteros> resultado = SELECT_WHERE_Pist(db);
                if (resultado.Count() > 0)
                {
                    PisterosLista = resultado.Cast<Pisteros>().ToList();
                    //Console.WriteLine("content :: " + content);
                    Console.WriteLine("Data :: " + PisterosLista);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public static IEnumerable<T_Pisteros> SELECT_WHERE_Pist(SQLiteConnection db)
        {
            return db.Query<T_Pisteros>("SELECT * FROM T_Pisteros");
        }

if the column IDPromo is an int, then just do this

    IEnumerable<int> resultado = SELECT_WHERE(db);

    public static IEnumerable<int> SELECT_WHERE(SQLiteConnection db)
    {
        return db.Query<int>("SELECT IDPromo FROM T_Promo");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM