The Entity Framework 4.1 supports code First programming mode: You can create a model class first, and then dynamically build the database under EF4.1 by configuration.
Two scenarios are shown below:
1, Code First mode, ASP. NET MVC data access
2, traditional mode, first create the database and table, configure the connection string, and then generate the model
Steps for the first case:
(1) Using an empty template, create an ASP. MVC3.0 (or 4.0) project, assuming the project name: mvc_student
Note: When you finish creating the project, the project automatically references EF4.1
(2) Under the Model folder, create the database context class: Studbcontext
public class Studbcontext:dbcontext
{
Public Studbcontext ()
: Base ("DataConn")
{
}
Public dbset<studentinfo> Students {get; set;}
}
(3) Create a domain model: studentinfo
public class Studentinfo
{
public int ID {get; set;}
public string Stuno {get; set;}
public string Stuname {get; set;}
public string Stuphoto {get; set;}
Public DateTime Stubirthday {get; set;}
public string Stuaddress {get; set;}
}
(4) Configure the connection string in Web. config (also not configurable, EF automatically checks and uses SQL Server EXPRESS, where we specify the server and database)
<connectionStrings>
<!--<add name= "Studbcontext" connectionstring= "server= (local);d atabase=mystudent;uid= (login account);p wd= (login password)" Providername= "System.Data.SqlClient"/>-->
<add name= "dataconn" connectionstring= "server= (local);d atabase=mystudent;uid= (login account);p wd= (login password)" Providername= "System.Data.SqlClient"/>
</connectionStrings>
(5) Build the project and service for step (6)
(6) Right-click the "Controllers" folder, select "Add Controller",
When you click OK, a Studentcontroller class is generated under the Controllers folder, and the student subfolder is generated under the Views folder, which contains 5. cshtml files,
(8) Finally, click on the "Debug" menu and select "Start Debugging"
(9) You can click the "Create New" hyperlink to add a record to the database
At this point, you can open the database server and discover that the Mystudent database is automatically created (the database in the connection string) and the Studentinfoes table (the plural form of the model class name, and the fields in the table correspond to the properties in the Model class, respectively. It is important to note here that the id attribute automatically corresponds to the self-growing primary key column in the table.
The second method is similar to the first one, after creating the database and entity classes, you can make the database calls directly!
ASP. NET mvc+entity Framework Access database