Ef4.1 includes code first and dbcontext APIs. Dbcontext API provides EF with more working methods: code first, database first, and model first.
Use dbcontext Constructor
1. Code first convention connection
Namespace magic. Unicorn
{
Public class unicornscontext: dbcontext
{
Public unicornscontext ()
// C # Will Call base class parameterless constructor by default
{
}
}
}
Use magic. Unicorn. unicornscontext as the database name and generate the connection string (SQL express) of the database on the local machine ).
2. Code first specifies the agreed connection of the Database Name
Public class unicornscontext: dbcontext
{
Public unicornscontext ()
: Base ("unicornsdatabase ")
{
}
}
Use unicornsdatabase as the database name to generate the connection string (SQL express) of the database on the local machine ).
3. Use the connection string in the configuration file for code first
<Connectionstrings>
<Add name = "unicornscedatabase"
Providername = "system. Data. sqlserverce.4.0"
Connectionstring = "Data Source = unicorns. SDF"/>
</Connectionstrings>
Public class unicornscontext: dbcontext
{
Public unicornscontext ()
: Base ("name = unicornscedatabase ")
{
}
}
4. database/model first uses the connection characters in the configuration file
<Add name = "northwind_entities"
Connectionstring ="
Metadata = Res: // */northwind. CSDL |
Res: // */northwind. SSDL |
Res: // */northwind. MSL;
Provider = system. Data. sqlclient;
Provider connection string =
& Quot; Data Source =. \ sqlexpress;
Initial catalog = northwind;
Integrated Security = true;
Multipleactiveresultsets = true & quot ;"
Providername = "system. Data. entityclient"/>
Public class northwindcontext: dbcontext
{
Public northwindcontext ()
: Base ("name = northwind_entities ")
{
}
}