Entity Framework: DbContext and setting the ProviderName

前端 未结 3 1568
难免孤独
难免孤独 2020-12-10 10:53

When you derive from DbContext and use the parameter-less constructor it will load a connection string from web.config. You also have the option of explicitly specifying the

相关标签:
3条回答
  • 2020-12-10 11:17

    Try like this ,

    public DBDataContext _dataContex;
    
    public DBDataContext DBContext 
        {
            get
            {
                if (_dataContex== null)
                {
                    _v= new DBDataContext(ConfigurationManager.ConnectionStrings["yourConnectinString"].ConnectionString);
                }
                return _dataContex;
            }
    
        }
    
    0 讨论(0)
  • 2020-12-10 11:20

    Create your DbConnection manually and pass it to the DbContext constructor as follows:

    var conn = DbProviderFactories.GetFactory("MY_CONN_PROVIDER").CreateConnection();
    conn.ConnectionString = "MY_CONN_STR";
    
    new DbContext(conn, true);
    

    Notice the second parameter bool contextOwnsConnection is true. Since you don't re-use the connection elsewhere, it lets the context manage the connection and Dispose() it when needed.

    0 讨论(0)
  • 2020-12-10 11:29

    You can get to the ObjectContext through IObjectContextAdapter:

    ((IObjectContextAdapter)context).ObjectContext
    

    DbContext ("context" above) still wraps ObjectContext, so don't worry that you will have a new instance.

    You can instantiate DbContext using this overload

    public DbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext) {}
    

    for example:

    public class YourDbContext : DbContext 
    {
        public YourDbContext() : this(new YourObjectEntities(), dbContextOwnsObjectContext: true) 
        {}
    
    }
    

    Then you can set your connection string inside of YourObjectEntities:

    public partial class YourObjectEntities : ObjectContext
    {
        public const string ConnectionString = "name=YourEntities";  // Get it from somewhere
    
        public YourObjectEntities() : base(ConnectionString, "YourEntities")
        {
        // Some initialization, e.g. ContextOptions.LazyLoadingEnabled = false;
        }
    }
    

    How you specify the provider there is your exercise.

    0 讨论(0)
提交回复
热议问题