EF first database change connection string

1

Hi I have server with some databases that have the same schema. I use EF6 Database/Model First code and I do not want to create deterrent DbContext for them. for example my generated DbContext is :

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

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

    public virtual DbSet<Header> tbl_Headers { get; set; }
    public virtual DbSet<Output> tbl_Output { get; set; }
    public virtual DbSet<Run> tbl_Run { get; set; }
}

and I created a partial class to set the connection string

public partial class TEST_Rev5_FINALEntities : DbContext 
{
    public TEST_Rev5_FINALEntities(DbConnection dbConnection)
        : base(dbConnection, true)
    {
    }
}

And I have the following method to create the connection with deterrent connection string:

public DbConnection GetConnectionString()
{
    DbConnection conn;
    SqlConnectionStringBuilder sqlConnectionStringBuilder = new SqlConnectionStringBuilder
    {
        DataSource = DataSource,
        IntegratedSecurity = false,
        UserID = User,
        Password = Password,
        MultipleActiveResultSets = true
    };

    SqlConnectionFactory sqlConnectionFactory = new SqlConnectionFactory(sqlConnectionStringBuilder.ConnectionString);
    conn = sqlConnectionFactory.CreateConnection(DatabaseName);

    return conn;
}

Finally I try to run it like this:

using (var context = new TEST_Rev5_FINALEntities(_dal.Connector.GetConnectionString()))
{
    return context.tbl_Headers.FirstOrDefault();
}

but I get this error :

System.Data.Entity.Infrastructure.UnintentionalCodeFirstException
HResult=0x80131509 Message=The context is being used in Code First mode with code that was generated from an EDMX file for either Database First or Model First development.

How can I do it?

c#
entity-framework
asked on Stack Overflow Mar 28, 2018 by Liran Bar-Nes • edited Mar 28, 2018 by Liran Bar-Nes

1 Answer

1

The behavior EF uses depends on the way your connection string looks. If it includes a metadata attribute like this:

metadata=res://*/model.csdl|res://*/model.ssdl|res://*/model.msl;

It will presume you are using Database or Model first development.

To make sure Code First is used, remove metadata part of the connection string.

answered on Stack Overflow Mar 28, 2018 by Martin Zikmund

User contributions licensed under CC BY-SA 3.0