Changing schema name on runtime - Entity Framework

前端 未结 6 643
梦谈多话
梦谈多话 2020-12-01 04:12

I need to change the storage schema of the entities on runtime. I\'ve followed a wonderful post, available here: http://blogs.microsoft.co.il/blogs/idof/archive/2008/08/22/c

6条回答
  •  爱一瞬间的悲伤
    2020-12-01 04:25

    Not an answer per se but a followup on Jan Matousek's Create[EntityConnection] method showing how to use from a DbContext. Note DB is the DbContext type passed to the generic repository.

     public TxRepository(bool pUseTracking, string pServer, string pDatabase, string pSchema="dbo")
    {
        // make our own EF database connection string using server and database names
        string lConnectionString = BuildEFConnectionString(pServer, pDatabase);
    
        // do nothing special for dbo as that is the default
        if (pSchema == "dbo")
        {
            // supply dbcontext with our connection string
            mDbContext = Activator.CreateInstance(typeof(DB), lConnectionString) as DB;
        }
        else // change the schema in the edmx file before we use it!
        {
            // Create an EntityConnection and use that to create an ObjectContext,
            // then that to create a DbContext with a different default schema from that specified for the edmx file.
            // This allows us to have parallel tables in the database that we can make available using either schema or synonym renames.
            var lEntityConnection = CreateEntityConnection(pSchema, lConnectionString, "TxData");
    
            // create regular ObjectContext
            ObjectContext lObjectContext = new ObjectContext(lEntityConnection);
    
            // create a DbContext from an existing ObjectContext
            mDbContext = Activator.CreateInstance(typeof(DB), lObjectContext, true) as DB;
        }
    
        // finish EF setup
        SetupAndOpen(pUseTracking);
    }
    

提交回复
热议问题