在上下文中设置 Entity Framework 连接字符串

Set Entity Framework Connection String in context

我需要在上下文中设置我的 Entity Framework 连接字符串;

using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;

public partial class DERSANEM_MASTEREntities : DbContext
{
    public DERSANEM_MASTEREntities()
        : base("")
    {
    }

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

    public DbSet<sysdiagrams> sysdiagrams { get; set; }
    public DbSet<T_HATA_LOG> T_HATA_LOG { get; set; }
    public DbSet<T_MUSTERILER> T_MUSTERILER { get; set; }
}

你可以修改上下文class构造函数,并传递你的字符串连接的参数:

public DERSANEM_MASTEREntities(bool con = true) : base(ConnectionStringClass.GetConnectionString())
        {...
}

o:

public DERSANEM_MASTEREntities()
        : base("GetConnectionStringName")
    {...
    }

您可以使用 DbContext 构造函数并发送 connectionString 的名称。

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

    public partial class DERSANEM_MASTEREntities : DbContext
    {
        public DERSANEM_MASTEREntities()
            : base("MyDbConnection")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }    
        public DbSet<sysdiagrams> sysdiagrams { get; set; }
        public DbSet<T_HATA_LOG> T_HATA_LOG { get; set; }
        public DbSet<T_MUSTERILER> T_MUSTERILER { get; set; }
    }
}

更多信息:

//
// Summary:
//     Constructs a new context instance using the given string as the name or connection
//     string for the database to which a connection will be made. See the class remarks
//     for how this is used to create a connection.
//
// Parameters:
//   nameOrConnectionString:
//     Either the database name or a connection string.
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
public DbContext(string nameOrConnectionString);

感谢您的回答

我解决了这个问题

public partial class DERSANEM_MASTEREntities : DbContext
{
    public DERSANEM_MASTEREntities()            
    {
        this.Database.Connection.ConnectionString = CS_Sifreleme.Decrypt("TcF8EGfKWDbCdqgS.........");
    }

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

    public DbSet<sysdiagrams> sysdiagrams { get; set; }
    public DbSet<T_HATA_LOG> T_HATA_LOG { get; set; }
    public DbSet<T_MUSTERILER> T_MUSTERILER { get; set; }
}