我如何通过一个连接字符串,以数据库为先的DbContext与实体框架4.1的构造? [英] How do I pass a connection string to the constructor of a database-first DBContext with Entity Framework 4.1?

查看:396
本文介绍了我如何通过一个连接字符串,以数据库为先的DbContext与实体框架4.1的构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于种种原因,我想为不可以存储连接字符串为我的实体框架DB模式,在不同的.config文件之一。 (我用的新实体框架版本4.1,.NET 4和Visual Studio 2010的C#的最新和最伟大的DbContext API)。但是,对于的DbContext的code生成模板只创建一个参数的构造函数。 (如果我不使用的DbContext API,那么我的实体框架模型有7个不同的构造函数可供选择,包括我想要的。)

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

我能想出如何做到这一点是直接修改code-生成模板(context.tt文件),只有这样,才能给我我想要的(例如:code以下)的构造。这工作,但感觉就像我做的坚硬方式。什么是正确的方式来获得的DbContext构造函数,它接受一个连接字符串?

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 like 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);
#>
    }

最后要注意的情况下,它可能会帮助别人。虽然这种方法,我花了一段时间来认识到连接字符串没有严格的数据库连接字符串,而是特殊的实体框架的连接字符串,其中包含数据库连接字符串(就像你会被存储在应用程序config文件)。

推荐答案

你的方法貌似最正确的方式做到这一点。这就是为创建的T4模板,你基本上做同样的事情,该模型一做模板默认情况下。

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.

另一种可能性是使数据库上下文类是部分(如果它不是默认情况下),并创建另一个部分类文件,它旁边添加的构造函数,你想。但它很可能是你需要的您T4生成环境的全部的遵循这个模式,所以我认为这是最好的利用code代自动执行此操作你的方式做的问题。

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.

这篇关于我如何通过一个连接字符串,以数据库为先的DbContext与实体框架4.1的构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆