System.ObjectDisposedException HResult=0x80131622 Message=Cannot access a disposed object. Object name: 'SQLiteConnection'.
Source=System.Data.SQLite
I've written a simple repository that uses Dapper and DapperExtensions
When trying to retrieve some results, I get this error when using a Usingblock after the method returns to the view model. When replacing the Using block with Open/Close methods of the connection I don't receive an error. I feels like the issue is very simple, but I just don't see it.
My "base" DB repository
using System.Data.SQLite;
namespace WpfApp1.Data
{
    public class SqliteBaseRepository
    {
        public static string DbFile
        {
            get { return @"D:\PROJECTS\test.db"; }
            //get { return Environment.CurrentDirectory + "\\SimpleDb.sqlite"; }
        }
        public SQLiteConnection DbConnection()//dbconnection
        {
            return new SQLiteConnection("Data Source=" + DbFile);
        }
    }
}
Generic Repository:
    public class Repository<TPoco, TDatabase> 
            where TPoco : class
            where TDatabase : SqliteBaseRepository, new()
        {
            private TDatabase DB = new TDatabase();
            public IEnumerable<TPoco> FindAll(object predicate=null)
            {
                IEnumerable<TPoco> result;
                using (var cnn = DB.DbConnection())
                {
                    //var cnn = DB.DbConnection();
                    cnn.Open();
                    result = cnn.GetList<TPoco>(predicate);
                }
                return result;
            }
        }
In my View-Model's constructor, I get an error here:
public PartViewModel()
{
    var x = _PartRepository.FindAll();  //no error. There are results/data in here
    var y = new ObservableCollection<Part>(x); //error raised here
}
Using Open/Close instead of the Using block does not yield an error:            
public IEnumerable<TPoco> FindAll(object predicate=null)
                {
                    IEnumerable<TPoco> result;
                    var cnn = DB.DbConnection();
                    cnn.Open();
                    var result = cnn.GetList<TPoco>(predicate);
                    cnn.Close();
                    return result;
                }
You need to iterate the result inside the using block:
using (var cnn = DB.DbConnection())
{
    //var cnn = DB.DbConnection();
    cnn.Open();
    result = cnn.GetList<TPoco>(predicate);
    result = result.ToList();  // fetch records now 
}
return result;
A Linq query is 'lazy', the actual Db I/O is postponed. In your original case til after you closed the connection.
User contributions licensed under CC BY-SA 3.0