Arno 2501
Arno 2501

Reputation: 9397

Must pass connection string to EF 5 DbContext code first else Command Exception

I m just using EF 5.0 and I've recreated a very simple DbContext that was working as is with EF 4.1.

Here context and model

public class AgenciesDatabaseContext : DbContext 
{
   public DbSet<Agency> Agencies { get; set; }
}

[Table("QryAgency")]
public class Agency
{
   [Key]
   public string CardCode { get; set; }
   public string DisplayName { get; set; }
   public string CardFName { get; set; }
   public string Address { get; set; }
   public string ZipCode { get; set; }
   public string City { get; set; }
}

I set in global.asax initializer for this context as null because the table already exists

Database.SetInitializer<ExtranetCentralizerContext>(null);

Here's the connection string in web.config :

<add name="AgenciesDatabase" providerName="System.Data.SqlClient" connectionString="..."/>

When I try to use the DbContext in the repository I get this error :

InnerException = {"Invalid column name '...'.\r\n Invalid column name '...'.\r\nInvalid column name '...'."}

It's strange because I could see that there is not connection made to my database.

What I don't understand is that I can make it work if I pass the connection string to the context like this :

 public class AgenciesDatabaseContext : DbContext 
 {
     public DbSet<Agency> Agencies { get; set; }

     public AgenciesDatabaseContext ()
            : base("AgenciesDatabase")
     {

     }
 }

There everything work fine. So my question is : isn't EF suposed to use the connection string that matches it's name (in this case AgenciesDatabase) ??? What makes it fail in this case ?

Upvotes: 2

Views: 970

Answers (1)

tschmit007
tschmit007

Reputation: 7800

in your app.config the name should be AgenciesDatabaseContext, not only AgenciesDatabase.

Upvotes: 3

Related Questions