16

I am using Entity Framework 5.0 for my project. I looked on the internet and I saw that for the entity framework data context there was another constructor that had a string parameter for the connection string.

On my generated data context I don't have such a constructor. I looked into the base DbContext and it has such a constructor.

Was the code generated wrong? I generated the code from a database. Could this be the cause?

Turns out that I can edit the code generation template file to add the new constructor. Now I have added the new constructor. The file is a MyDataContext.tt file under your edmx model. There you have c# code mixed with template code. You can copy the no argument constructor from there and paste it bellow. Then you can change it and add a string argument to it and pass that argument to the DbContext constructor like this : base(myString).

7
  • 1
    Can you post the codes to make the difference more clear ..? Commented Jan 6, 2013 at 12:31
  • What is stopping you from adding it manually? Commented Jan 6, 2013 at 12:34
  • Also, DbContext is "Code-First". If you have an existing database, the typical usage is "Database-First". Commented Jan 6, 2013 at 12:35
  • @flem With EF5 even database first generates the dbcontext classes for you. It uses T4 files Commented Jan 6, 2013 at 12:38
  • @scartag. I thought db-first used ObjectContext? Did it change in EF5? Commented Jan 6, 2013 at 12:40

1 Answer 1

23

You can add one as needed.

Check the generated file and add an overloaded constructor.

public YourContext(string connectionStr)
        : base(connectionStr)
    {


    }

Probably better to define this in a partial class though, as every generation will require you to manually add it each time.

Sign up to request clarification or add additional context in comments.

5 Comments

I believe I can also edit the .tt file but I don't know if this file is a autogenerated too.
tested and changed the .tt file adding a new constructor in it. works now
@Alecu: I had the same problem and did the same thing: good to know!
I agree with scartag it is better to define it in a partial class, as every-time your code is generated you will loose your customisations. And it's easier to do that than edit the tt files.
NOTE: In order to set the ConnectionString programatically, make sure you don't format it like the one in web.config or app.config. That one will contain " which needs to be changed to single quotes, or you will get a most unhelpful error message. stackoverflow.com/questions/6997035/… . Either that, or use the EntityConnectionStringBuilder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.