Now let's learn how Code first sets the name of the database when the database is initialized.
The following figure shows the workflow of database initialization, initialized according to the arguments passed to the constructor of the context base class:
According to the diagram above, the constructor of the context base class can pass in the following parameters:
- No parameters
- parameter is the database name
- parameter is a connection string
constructor with no parameters:
If you do not pass arguments to the constructor of the context base class, it will create a {namespace} locally on our own. {Context class name} is the name of the database. For example, the following code will create a database named schooldatalayer.context
namespace schooldatalayer{ publicclass context:dbcontext { public Base() { } }}
constructor to pass in the database name:
We can also specify a database name to pass as a parameter to the context constructor, so that locally we will create a database with the name of the passed parameter. As the following code, a database called Myschooldb is created
namespace schooldatalayer{ publicclass context:dbcontext { public base("myschooldb") { }} }
Constructor for incoming connection string:
After we have defined the connection string in app. Config or Web. config, we can also pass the format of the "Name=" + connection string as a parameter to the context constructor. As the following code, we pass in the constructor of the name=schooldbconnectionstring to the context
namespace schooldatalayer{ publicclass context:dbcontext { public base("name=schooldbconnectionstring") { } } }
App. Config:
<?XML version= "1.0" encoding= "Utf-8"?><Configuration> <connectionStrings> <Addname= "Schooldbconnectionstring"connectionString= "Data source=.;i Nitial catalog=schooldb-byconnectionstring;integrated security=true "ProviderName= "System.Data.SqlClient"/> </connectionStrings></Configuration>
In the context class above, we pass the connection string to its constructor, note that the connection string name must start with "name=", otherwise Code-first will use it as the database name. Because the database name of the connection string in app. config is schooldb-byconnectionstring, Code-first creates a Schooldb-byconnectionstring A named database or use a database that already exists with the same name. Also, make sure that the connection string in app. config contains the providername = "System.Data.SqlClient" attribute.
Summary: Code-first initializes the database by using different parameters passed in to the base class constructor.
EntityFramework Code-first Easy Tutorial (iii)-------database initialization