动态DbContext字符串不起作用

时间:2015-11-09 20:50:22

标签: c# entity-framework

我使用EF6(db first),我想在Settings.settings文件中设置我的数据库设置(服务器,目录)。我创建了一个像这样的部分类:

namespace MyApp
{
    public partial class MyAppEntities : DbContext
    {
        public MyAppEntities(String connString)
            : base(BuildConnectionString("SERVERNAME", "DATABASE"))
        {
        }

        private static String BuildConnectionString(String DataSource, String Database)
        {
            SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
            sqlBuilder.DataSource = DataSource;
            sqlBuilder.InitialCatalog = Database;
            sqlBuilder.PersistSecurityInfo = true;
            sqlBuilder.IntegratedSecurity = true;
            sqlBuilder.MultipleActiveResultSets = true;

            return sqlBuilder.ToString();
        }
    }
}

当我运行我的应用程序(WinForm)时,它没有点击这个部分类并使用EF6创建的MyAppEntities.Context.cs文件中的MyAppEntities类:

namespace MyApp
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class MyAppEntities : DbContext
    {
        public MyAppEntities()
            : base("name=MyAppEntities")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<Table1> Table1 { get; set; }
        public virtual DbSet<Table2> Table2 { get; set; }
    }
}

在我的应用程序(Form1.cs)中,我做了类似的事情:

using(MyAppEntities context = new MyAppEntities())
{
    var tableData = context.Table1.ToList();
}

我做错了什么?

2 个答案:

答案 0 :(得分:1)

如果你想一下你的部分类在合并到一个类时的样子,它将有两个构造函数......一个是string而另一个是无参数:

    public MyAppEntities(String connString)
        : base(BuildConnectionString("SERVERNAME", "DATABASE"))
    {
    }

    public MyAppEntities()
        : base("name=MyAppEntities")
    {
    }

当你创建类的实例时,你调用paremeterless的一个,它用"name=MyAppEntities"调用基类,而不是用字符串调用BuildConnectionString方法的构造函数。

MyAppEntities context = new MyAppEntities()

答案 1 :(得分:0)

您可以声明额外的部分类来扩展现有的部分类。

partial class MyAppEntities
{
  public MyAppEntities(string nameOrConnectionString)
    : base(nameOrConnectionString)
  {
  }
}

BuildConnectionString移到某个地方......也许是一些助手类。 并在DbContext初始化之前传递connectionString

var connectionString = DbHelper.BuildConnectionString("SERVERNAME", "DATABASE");
using(MyAppEntities context = new MyAppEntities(connectionString))
{
    var tableData = context.Table1.ToList();
}