I'm sure this will be a simple fix to a trained eye, but apparently my eyes are not trained enough...
I'm using Xamarin.Forms .Netstandard 2.0 project with EF and SQLite. I am able to: create database, put data into database. I am unable to: get data OUT of database.
I have the plumbing code in Android and iOS projects which obtain the proper path to the "db3" file. I pass that path to the app.xaml.cs and set that to a static var so it's available everywhere.
I have a class which inherits from "DbContext". In it is a "DbSet Cats {get; set;}" statement. The constructor accepts the path and calls the "Database.EnsureCreatedAsync()". I know this works, I can ADB pull the db and all tables are created.
I can use the context and "add" and "savechanges" to put data into the db. This works, I've confirmed the data are in there.
when I go to query the db, I've tried everything and keep getting this error, object reference....
I don't see any "dbConnection" code per se. I have in my context class the "onConfiguring" method and have confirmed it gets the right db path.
I've scoured the web and the examples. I think I have all the pieces, but obviously something is missing or done incorrectly. Here's some code:
public class DatabaseContext : DbContext
{
string _dbPath;
public DbSet<Cat> Cats { get; set; }
public DatabaseContext(string dbPath)
{
_dbPath = dbPath;
Database.EnsureCreatedAsync();
}
public async Task<IEnumerable<Cat>> GetCats()
{
var allCats = await Cats.ToListAsync().ConfigureAwait(false);
return allCats;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Filename={_dbPath}");
}
}
List<Cat> itemSource;
// Create Database & Tables
using (var db = new DatabaseContext(App.dbPath))
{
// Ensure database is created
db.Database.EnsureCreated();
// Insert Data
db.Add(new Cat() { IdCat = "111", Fname = "Felix1" });
db.SaveChanges();
// Retreive Data
//method 1
// RESULT: no data are in "itemsource", info reads "exception count = 1"
itemSource = db.Cats.ToList();
// method 2
// RESULTS: crashes with error "System.NullReferenceException: Object reference not set to an instance of an object."
Task<IEnumerable<Cat>> p = db.GetCats();
itemSource = db.Cats.ToList();
}