问题
I seem to have an issue creating an MVC4 application where I have adopted the code-first approach to creating my models but no connection string seems to have been created in the web.config file.
The constructed database seems to have been built on (localhost)\SQLEXPRESS instance but I would like to change this to an external data source. Without a connection string to update I'm not sure how to do this.
Please could someone point me in the right direction?
EDIT: I found the following diagram which highlights what the answers have said pretty well
(source: entityframeworktutorial.net)
回答1:
You have to add a connection string yourself
<add name="SomeDb" connectionString="Data Source=SERVENAME;Initial Catalog=DBNAME;User Id=loginid;Password=password" providerName="System.Data.SqlClient" />
Name of this string should match to the name of your context class.
public class SomeDb: DbContext
{
public SomeDb()
: base("name=SomeDb")
{
}
}
This should do it.
回答2:
If you use ADO.NET Entity Framework(.edmx) it will update your web.config file with connection string. but in code-first you need to write your connection string in web.config like,
suppose you dbcontext looks like,
public class SampleDbContext:DbContext
{
public SampleDbContext():base("SampleDbContext")
{
}
...
...
}
after you should create your connection string in web.config with SampleDbContext
name like,
Hope this helps
回答3:
You have to create a connection string with the same name as your DbContext
class:
<connectionStrings>
<add name="NameOfDbContext" connectionString="Data Source=ServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
You can also specify the connection string yourself using an overload of the DbContext
class:
public class MyDbContext() : base("ProductionDbContext")
{
}
Now you can use ProductionDbContext
as connection string.
See this article on MSDN for more information.
来源:https://stackoverflow.com/questions/19315048/code-first-change-data-source-without-connection-string