Using EF and SqLite - keep getting "object reference not set to an instance of an object"

XamarinNewbeeXamarinNewbee USMember ✭✭

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();
}

Answers

  • XamarinNewbeeXamarinNewbee USMember ✭✭

    FYI - I added the "Microsoft.EntityFrameworkCore.Sqlite" Nuget package to all projects. That's the only "plug-in" I'm using for data access. Do I need another? My understanding is that going the EF route is better than the other plug-in, "sqlite-net-pcl"???

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    NullReference... exception.
    Not at all Xamarin - just C#
    Tutorial on debugging this exception: http://www.dreamincode.net/forums/topic/258551-what-does-this-error-mean-understanding-the-common-errors/

  • XamarinNewbeeXamarinNewbee USMember ✭✭

    From the standpoint of utilizing Xamarin, Sqlite, EntityFramework, the real question is WHY am I getting this error? Why is the context and/or connection and/or other not instantiated at that point? What's missing?

  • ClintStLaurentClintStLaurent USUniversity ✭✭✭✭✭

    @XamarinNewbee said:
    From the standpoint of utilizing Xamarin, Sqlite, EntityFramework, the real question is WHY am I getting this error?

    Well... What is it saying is null? What object is null?

    Why is the context and/or connection and/or other not instantiated at that point?

    Because you didn't instantiate it? Just a guess.

    That's why I linked you the article. You have find the null reference. What is it that's null? Then work backwards from there to figure out where you need to instantiate it... or why the instance you thought you made earlier has gone out of scope and gotten garbage collected. Those are the two things I can think of off the top of my head.

  • JohnHardmanJohnHardman GBUniversity mod

    @XamarinNewbee said:
    From the standpoint of utilizing Xamarin, Sqlite, EntityFramework, the real question is WHY am I getting this error? Why is the context and/or connection and/or other not instantiated at that point? What's missing?

    As @ClintStLaurent said, this is C# debugging stuff, rather than Xamarin.
    The first thing to look at is the StackTrace that forms part of the Exception. You can either catch this in the debugger, or view it in the IDE's Output window. If you don't know how to interpret a StackTrace, post it here.

  • XamarinNewbeeXamarinNewbee USMember ✭✭

    I see what you mean by it's "C#" and not "Xamarin". I guess it's really C#, Entityframework and Sqlite at this stage. Wish I knew what was not instantiated. I've tried reinstantiating to be certain no scope issues, at least as best I know how. I'll try more closely looking at stack trace to see if it offers anything further. Thanks for trying :)

  • XamarinNewbeeXamarinNewbee USMember ✭✭
    edited April 4

    Hello again. I've gotten past this error. I can't swear its exact cause, but it likely relates to the dbContext and the way I was structuring things.

    So now I have a follow-up question... right now I'm establishing a public static dbContext variable in the app.cs. I was going to then use that throughout the program.

    1. does that work, and
    2. is that approach "bad practice" or "commonly done" ?

    Also, with EF in this setting (Xamarin.Forms and Sqlite), should I be using a repository?

  • JohnHardmanJohnHardman GBUniversity mod

    @XamarinNewbee said:
    1. does that work

    Yes

    @XamarinNewbee said:
    2. is that approach "bad practice" or "commonly done" ?

    Make it a property rather than a variable.
    It is commonly done.
    Whether it is bad practice is open to debate.

Sign In or Register to comment.