Entity Framework DefaultConnectionFactory being ignored

前端 未结 2 383
陌清茗
陌清茗 2021-01-07 03:52

I\'m using Entity Framework 5 with Code First. I\'ve written a custom IDbConnectionFactory which I want to use for all the connections made by my DbContex

相关标签:
2条回答
  • 2021-01-07 04:39

    You need to get the connection that you built for each call that you are wanting to use. For example using the following code.

    private static void UsingCustomConnection()
    {
        using (var conn = Database.DefaultConnectionFactory.CreateConnection("YourDbName"))
        {
            using (var context = new YourContext(conn))
            {
                context.Destinations.Add(new Destination {Name = "Colorado"});
                context.SaveChanges();
            }
        }
    }
    

    You will need to setup this in YourContext

    public YourContext(DbConnection connection)
        : base(connection, contextOwnsConnection: false)
    {
    
    }
    
    0 讨论(0)
  • 2021-01-07 04:50

    I know it is not ideal but this worked for me:

    public class DBBase : DbContext
    {
        public DBBase(string nameOrConnectionString)
            : base(Database.DefaultConnectionFactory.CreateConnection(nameOrConnectionString), true)
        {
        }
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题