Entity Framework: DbContext and setting the ProviderName

前端 未结 3 1569
难免孤独
难免孤独 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: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.

提交回复
热议问题