开发者

How do I pass a connection string to the constructor of a database-first DBContext with Entity Framework 4.1?

开发者 https://www.devze.com 2023-04-09 14:47 出处:网络
For various reasons I would like to not store the connection string for my Entity Framework DB model in one of the various .config files.(I am using the latest and greatest DBContext API with the new

For various reasons I would like to not store the connection string for my Entity Framework DB model in one of the various .config files. (I am using the latest and greatest DBContext API with the new Entity Framework version 4.1, .NET 4 and Visual Studio 2010 C#.) However, the code generation template for DBContext only creates a single parameterless constructor. (If I don't use the DBContext API, then my entity framework model has 7 different constructors to chose from, including the one I want.)

The only way I could figure out how to do this was to directly modify the code-generation template (context.tt file) to give me the constructor I want (example code below). This works, but it feels li开发者_运维知识库ke I'm doing it "the hard way". What is the correct way to get a DBContext constructor that accepts a connection string?

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

One final note in case it might help somebody else. Although this method works, it took me a while to realize that the "connection string" is not strictly the DB connection string, but rather the special entity framework connection string which contains the DB connection string (just like what would be stored in the app.config file).


Your approach looks like the most correct way to do this. It's what the t4 templates were created for, and you're basically doing the same thing that the model-first templates do by default.

Another possibility would be to make the db context class be partial (if it isn't by default) and create another partial class file alongside it to add the constructor you want. But it seems likely that you'll want all of your t4-generated contexts to follow this pattern, so I think it's best to leverage the code generation to do this automatically the way you do in the question.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号