C# 如何首先使用实体框架代码将ConnectionString与DbContext一起使用?

C# 如何首先使用实体框架代码将ConnectionString与DbContext一起使用?,c#,entity-framework,C#,Entity Framework,我正在使用Windows窗体应用程序,并已将Entity Framework 6添加到该项目中。我已经创建了一个类,我可以在其中传递表名,这样我就可以将一个类与许多不同的表一起使用。我想先在没有向导的情况下使用EF代码。如何设置DbContext的连接字符串?我知道在ASP.NET MVC中,您可以在app.Config文件中进行设置,但这是一个Windows窗体应用程序。如何设置连接字符串以从SQL Server获取数据 public class TimerContext : DbContex

我正在使用Windows窗体应用程序,并已将Entity Framework 6添加到该项目中。我已经创建了一个类,我可以在其中传递表名,这样我就可以将一个类与许多不同的表一起使用。我想先在没有向导的情况下使用EF代码。如何设置DbContext的连接字符串?我知道在ASP.NET MVC中,您可以在app.Config文件中进行设置,但这是一个Windows窗体应用程序。如何设置连接字符串以从SQL Server获取数据

public class TimerContext : DbContext
{
    private readonly string _tableName;

    public TimerContext(string tableName) : base("name=TimerContext")
    {
        _tableName = tableName;
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Timer>().ToTable(_tableName);

        base.OnModelCreating(modelBuilder);
    }

    public IEnumerable<Timer> Timers { get; set; }
}
公共类TimerContext:DbContext
{
私有只读字符串_tableName;
公共TimerContext(字符串tableName):base(“name=TimerContext”)
{
_tableName=tableName;
}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable(_tableName);
基于模型创建(modelBuilder);
}
公共IEnumerable计时器{get;set;}
}

右键单击项目,选择添加->新项目->应用程序配置文件

在新创建的app.config文件中添加连接字符串,就完成了