没有构造与实体框架的DataContext的连接字符串字符串、实体、框架、DataContext

2023-09-04 02:04:25 作者:握不住的沙

我使用实体框架5.0 我的项目。我看着在互联网上,我看到了实体框架数据方面还有一个构造有用于连接字符串的字符串参数。

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.

在我的生成数据上下文我没有这样的构造函数。我看着基的DbContext ,它有这样的构造。

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

曾是code产生错了吗?我产生从数据库中code。难道这是原因?

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

原来,我可以编辑code生成模板文件中添加新的构造。现在,我已经添加了新的构造函数。该文件是在你的EDMX模型MyDataContext.tt文件。有你有C#code与模板code混合。你可以从那里复制的无参数的构造函数,并将其粘贴波纹管。然后,你可以改变它,并添加一个字符串参数,并传递参数给的DbContext构造是这样的:基地(MyString的)

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

推荐答案

您可以根据需要添加的。

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.