No constructor with a connection string in Entity

2020-06-08 13:01发布

问题:

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).

回答1:

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.