locked
Passing a ConnectionString in DbContext Constructor RRS feed

  • Question

  • I was using Entity Framework 4.0 and am trying to upgrade to either 5.0 or (preferably) 6.0.  I made all the changes listed for 6.0 and switched to DbContext from ObjectContext.  Everything compiles just fine whether I generate the code with EF 5.x DbContext Generator or (preferably) ADO.NET DbContext Generator with WCF Support.  However, I am having some problems with my connection string.  I need to set this dynamically in the code, but there is no option for passing the actual connection string--only the name used in the app.config file.  I did add another constructor for my DbContext as follows:

    public partial class MyEntities : DbContext
    {
        public MyEntities(string paramType, string connectionString)
            : base(connectionString)
        {
            Database.Connection.ConnectionString = connectionString;
        }
    }

    However, now when I run the code, I can create the DbContext, but when I try to run LINQ on one of the DbSet objects, I get an UnintentionalCodeFirstException in OnModelCreating.  This occurs no matter which generator I use for the T4 templates and in both EF 5.0 and EF 6.0.  The full error is listed below:

    Code generated using the T4 templates for Database First and Model First development may not work correctly if used in Code First mode. To continue using Database First or Model First ensure that the Entity Framework connection string is specified in the config file of executing application. To use these classes, that were generated from Database First or Model First, with Code First add any additional configuration using attributes or the DbModelBuilder API and then remove the code that throws this exception.

    I have tried to override the OnModelCreating as described in this post, but then it actually tries to create a new model and has problems with some of our tables in the database.  Obviously, I don't want to do that anyway.   

    Is there something more I need to do or am I just using the wrong generators?  Can you use DbContext with Database First or do I need to stay with ObjectContext?  I thought that was now obsolete.  I should mention that I am still using VS2010.

    Thanks in advance for your help!


    Christine A. Piffat

    Thursday, September 26, 2013 9:13 PM

Answers

  • Hello,

    If I understand correctly, you want to know how to specify the Database while creating the instance for the DbContext with DB or Model First. (I assume that because you mentioned “only the name used in the app.config file”.)

    I have a look at the POST, however, it used the Code First model rather than DB or Model First.

    For this problem “Code generated using the T4 templates for Database…,”, as far as I know, it is caused by the wrong connectionstring, when we are using model-first / database-first (EDMX) we must use Entity connection string with referencing .ssdl, .msl and .csdl metadata files.

    If we want to specify the connectionString while using DB or Model First, we need write it like below:

    DataBaseFirstDBEntities db1 = new DataBaseFirstDBEntities("metadata=res://*/DBFirstModel.csdl|res://*/DBFirstModel.ssdl|res://*/DBFirstModel.msl;provider=System.Data.SqlClient;provider connection string=\"data source=(localdb)\\v11.0;initial catalog=DataBaseFirstDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework\"");
    
    
                List<Order> orderList = (from o in db1.Orders
    
                                         select o).ToList();
    
    
                return orderList;
    
    public DataBaseFirstDBEntities()
    
                : base("name=DataBaseFirstDBEntities")
    
            {
    
            }
    
    
            public DataBaseFirstDBEntities(string connectionString)
    
                : base(connectionString)
    
            {
    
            }
    

    If I have misunderstood, please let me know.

    Thanks &Regards.

    • Edited by Fred Bao Friday, September 27, 2013 8:30 AM Better
    • Marked as answer by Christy Piffat Friday, September 27, 2013 2:48 PM
    Friday, September 27, 2013 8:28 AM

All replies

  • Hello,

    If I understand correctly, you want to know how to specify the Database while creating the instance for the DbContext with DB or Model First. (I assume that because you mentioned “only the name used in the app.config file”.)

    I have a look at the POST, however, it used the Code First model rather than DB or Model First.

    For this problem “Code generated using the T4 templates for Database…,”, as far as I know, it is caused by the wrong connectionstring, when we are using model-first / database-first (EDMX) we must use Entity connection string with referencing .ssdl, .msl and .csdl metadata files.

    If we want to specify the connectionString while using DB or Model First, we need write it like below:

    DataBaseFirstDBEntities db1 = new DataBaseFirstDBEntities("metadata=res://*/DBFirstModel.csdl|res://*/DBFirstModel.ssdl|res://*/DBFirstModel.msl;provider=System.Data.SqlClient;provider connection string=\"data source=(localdb)\\v11.0;initial catalog=DataBaseFirstDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework\"");
    
    
                List<Order> orderList = (from o in db1.Orders
    
                                         select o).ToList();
    
    
                return orderList;
    
    public DataBaseFirstDBEntities()
    
                : base("name=DataBaseFirstDBEntities")
    
            {
    
            }
    
    
            public DataBaseFirstDBEntities(string connectionString)
    
                : base(connectionString)
    
            {
    
            }
    

    If I have misunderstood, please let me know.

    Thanks &Regards.

    • Edited by Fred Bao Friday, September 27, 2013 8:30 AM Better
    • Marked as answer by Christy Piffat Friday, September 27, 2013 2:48 PM
    Friday, September 27, 2013 8:28 AM
  • Thanks!!  I had tried using the Entity Connection String with Database.Connection.ConnectionString, which didn't work, but had not thought about putting it in the constructor. 

    Christine A. Piffat

    Friday, September 27, 2013 2:49 PM
  • public DataBaseFirstDBEntities(string connectionString) : base(connectionString) { }

    the above entry we need to add manually rite. It is not generated by default. The problem is new

    manually added code gets cleared once we do an update from database. How to solve that


    Friday, September 5, 2014 7:11 PM
  • You should be able to modify your context template (tt) file by adding a second constructor to the template. Then when the class file is generated it will include your added constructor. Probably something like:

    public <#=code.Escape(container)#>(string connectionString)
            : base(connectionString)
        {
        }

    • Proposed as answer by laberko Thursday, April 21, 2016 9:11 AM
    Tuesday, October 7, 2014 9:40 PM
  • Actually, it would look more like this (mind you, this is in VB):

    When modifying the template, select and copy the code for the constructor, then change the first two lines of the second constructor.

    In constructor #2, replace this:

    Public Sub New ()
    MyBase.New("name=<#=container.Name#>")

    --with this:

    Public Sub New(ByVal ConnectionString As String)
    MyBase.New(ConnectionString)

    You should save the second constructor part somewhere else in your program, in case you subsequently modify the model, and have to paste constructor #2 back into the context file. For instance, have a module contain the following commented code:

    ' Public Sub New(ByVal ConnectionString As String)
    ' MyBase.New(ConnectionString)

    ' ... '(remaining code)

    ' End Sub


    Robert Gustafson



    Tuesday, June 21, 2016 8:07 PM