The EntityFramework database connection can be dynamically set by code, entityframework
From: http://blog.csdn.net/dyllove98/article/details/9289553
Database generation location controllable (mainly DbContext constructor)
1. Use the DbContext Constructor: Public DbContext (string nameOrConnectionString)
A. Add the following in app. config:
1 <connectionStrings>2 <add name="CodeFirstBlogContext" providerName="System.Data.SqlClient" connectionString="Server=.;Database=CodeFirstBlog;uid=sa;pwd=sa" />3 </connectionStrings>
Note: of course here you can also add to use other databases, but to mention the installation of the driver: Reference can refer to this article: http://www.cnblogs.com/yylp521/p/3173176.html
B. Add the constructor to the data context class (it was not displayed in the past, and the default calling is generally the local. \ sqlexpress database instance)
1 public BlogContext(string config)2 : base(config)3 {4 }
The reference configuration library in the configuration file can be displayed here. Note: config can directly write name = CodeFirstBlogContext, which is the name under connectionStrings in the configuration file.
2. Use the DbContext Constructor: Public DbContext (DbConnection existingConnection, bool contextOwnsConnection)
A. Add the constructor to the data context class (it was not displayed in the past, and the default calling is generally the local. \ sqlexpress database instance)
1 public BlogContext(DbConnection connection,bool contextOwnsConnection)2 : base(connection, contextOwnsConnection) 3 { }
B. Create a Connection during use.
1 string connStr = "Server = .; database = CodeFirstBlog2; uid = sa; pwd = sa "; 2 using (SqlConnection conn = new SqlConnection (connStr) 3 {4 using (var db = new BlogContext (conn, false) 5 {6 Console. writeLine ("enter a new Blog name"); 7 var name = Console. readLine (); 8 9 var blog = new Blog {Name = name}; 10 db. blogs. add (blog); 11 db. saveChanges (); 12 13 var query = from B in db. blogs14 orderby B. name15 select B; 16 17 foreach (var item in query) 18 {19 Console. writeLine (item. name); 20} 21} 22} 23 Console. readKey ();
3. Use the data connection Factory
1 Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Server=.\sqlexpress;Database=CodeFirstBlog4;uid=sa;pwd=sa");2 using (var db=new BlogContext())3 {4 db.Database.Initialize(true);5 db.Blogs.Add( new Blog { Name = "test" });6 db.SaveChanges();7 }
Note: The Database name specified here is invalid. It should be related to the Database Initialize method and will be verified.
4. Other DbContext constructor functions are available. You can view the implementation of the DbContext class directly.