实体框架DbContext实例DataReader已经打开

时间:2017-12-16 00:29:52

标签: c# mysql entity-framework

我对实体框架没有多少经验,所以我会尝试提供尽可能多的信息,尽量不要让它太长。

这是我的DbContext:

using MySql.Data.Entity;
using MySql.Data.MySqlClient;
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Migrations;

namespace src.Database.Models
{
    [DbConfigurationType(typeof(MySqlEFConfiguration))]
    public class DefaultDbContext : DbContext
    {
        public DefaultDbContext(string connectionString) : base(connectionString)
        {
            System.Data.Entity.Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultDbContext, MigrationConfiguration>());
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Character> Characters { get; set; }
        public DbSet<CharacterClothes> CharacterClothes { get; set; }
        public DbSet<CharacterVehicles> CharacterVehicles { get; set; }
        public DbSet<Dealership> Dealership { get; set; }
        public DbSet<DealershipVehicle> DealershipVehicles { get; set; }
    }

    public class ContextFactory : IDbContextFactory<DefaultDbContext>
    {
        private static string ConnectionString;

        public static void SetConnectionParameters(string serverAddress, string username, string password, string database, uint port = 3306)
        {
            var connectionStringBuilder = new MySqlConnectionStringBuilder()
            {
                Server = serverAddress,
                UserID = username,
                Password = password,
                Database = database,
                Port = port
            };

            ConnectionString = connectionStringBuilder.ToString();
        }

        private static DefaultDbContext _instance;

        public static DefaultDbContext Instance
        {
            get
            {
                if (_instance != null) return _instance;
                return _instance = new ContextFactory().Create();
            }
            private set { }
        }

        public DefaultDbContext Create()
        {
            if (string.IsNullOrEmpty(ConnectionString)) throw new InvalidOperationException("Please set the connection parameters before trying to instantiate a database connection.");

            return new DefaultDbContext(ConnectionString);
        }
    }

    internal sealed class MigrationConfiguration : DbMigrationsConfiguration<DefaultDbContext>
    {
        public MigrationConfiguration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            SetSqlGenerator("MySql.Data.MySqlClient", new MySqlMigrationSqlGenerator());
        }
    }
}

所以,它正在为我所访问的所有连接使用一个实例:

var user = ContextFactory.Instance.Users.FirstOrDefault(x => x.id == id);
var dealerships = ContextFactory.Instance.Dealership.ToList();

它工作正常!

虽然,偶尔但我收到此错误:

已经有一个与此Connection关联的开放DataReader,必须先关闭。

我认为这是因为它正在尝试使用Instance,而它已经在使用中。

我一直在寻找如何解决它的日子,但我仍然无法使其发挥作用。我读过 MultipleActiveResultSets ,但我使用的是MySQL,似乎不支持。

1 个答案:

答案 0 :(得分:0)

你应该改变它

private static DefaultDbContext _instance;

[ThreadStatic]
private static DefaultDbContext _instance;

为每个线程/请求创建一个新的DBContext实例可能会更好。通过线程共享相同的DbContext是危险且令人反感的。这将导致不同的线程尝试使用它已经使用的相同DBContext实例。

另外,关于 UnitOfWork,事务管理以及为每个线程/请求创建DbContext的好处,有一篇非常好的文章here