重写code-产生的DbContext构造 [英] Overriding code-generated DbContext constructor

查看:147
本文介绍了重写code-产生的DbContext构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,我已经在某个阶段这样做过,但我无法弄清楚如何吧!我的情况:

I'm sure I've done this before at some stage, but I can't figure out how to now! My scenario:

// This is generated from EDMX
public partial class HOLDbEntities : DbContext
{
    public HOLDbEntities()
            : base("name=HOLDbEntities")
        {
        }
}

现在,我想这个连接字符串是很容易改变的(我想从HOLDbEntities实现的),所以我需要重写此构造函数。

Now, I want this connection string to be easily changeable (I want to Implement from the HOLDbEntities), so I need to override this constructor.

我已经试过:

public partial class HOLDbEntities
{
    private const string _contextName = "HOLDbEntities";
    public static string ContextName { get { return _contextName; } }

    public HOLDbEntities()
        : base(ContextName)
    {
    }
}

但是,这引发错误:

But this throw an error:

HOLDbEntities已经定义了一个名为HOLDbEntities具有相同的参数类型的成员。

HOLDbEntities already defines a member called "HOLDbEntities" with the same parameter types.

我可以理解为什么这个错误,但我将如何停止构造是自动生成的摆在首位,以做什么,我想达到什么目的?

I can understand why this errors, but how would I stop the constructor being auto-generated in the first place in order to do what I'm trying to achieve?

推荐答案

我可以建议最好的是一个工厂方法:

The best I can suggest is a factory method:

private HOLDbEntities(string contextName) : base(contextName) { }

public static HOLDbEntities Create() {
    return new HOLDbEntities(ContextName);
}

和使用 HOLDbEntities.Create(),而不是新HOLDbEntities()

这篇关于重写code-产生的DbContext构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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