开发者

Cannot change the connectionstring with Entity Framework 4.1 code first

I am having trouble changing the connection string used by entity framework code first for my project. I created a MVC3 project and then added two projects, DomainClasses and DataAccess.

The DomainClasses project has one class file named Classes.cs with one class:

public class User
{
    public int ID { get; set; }
    public string Username { get; set; }
    public string EmailAddress { get; set; }
    public string Password { get; set; }
    public int StatusID { get; set; }
    public DateTime DateCreated { get; set; }
}

The DataAccess project has one class file named PL开发者_如何学PythonNQDB.cs with one class:

public class PLNQDB : DbContext
{
    public DbSet<User> Users { get; set; }
}

I have a reference to each of these projects inmy MVC project and everything builds fine and runs and even creates the database file that I am able to save to and retrieve data from.

When running the project I can see in the Autos window the connection string being used under this.db.base.Database.Connection.base.ConnectionString =

"Data Source=.\\SQLEXPRESS;Initial Catalog=PLNQ.DataAccess.PLNQDB;Integrated Security=True;MultipleActiveResultSets=True"

My question is how do I override this autogenerated connectionstring to use my remote server. I have added a connection string to the web.config file of the MVC project.

  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="Data Source=255.255.255.255;Initial Catalog=PLNQ;User ID=blah;Password=blah"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

but everytime I run the project it still uses the auto generated connectionstring. I have also tried adding App.config files with the same connection string in both the DataAccess and DomainClasses projects.

What am I missing?


There are couple of options

1 You need to name the connection string that matches the your DbContext class name.

eg

  <connectionStrings>
    <add name="PLNQDB"
         connectionString="Data Source=255.255.255.255;Initial Catalog=PLNQ;User ID=blah;Password=blah"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

2 In your DbContext constructor call the base class constructor with the connection string name

public class PLNQDB : DbContext
{
    public PLNQDB():base("ApplicationServices"){}

    public DbSet<User> Users { get; set; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜