ASP. net mvc + Entity Framework 4.1

Source: Internet
Author: User
Tags sql server express

Entity Framework 4.1 supports code first programming mode: You can create a model class first, and then dynamically generate a database under ef4.1 by configuring.

The following shows two scenarios:

1. Asp.net MVC Data Access in code-first Mode

2. In traditional mode, create databases and tables, Configure connection strings, and then generate models.

 

Step 1:

(1) Create an ASP. NET mvc3.0 (or 4.0) project using an empty template. Assume that the project name is mvc_student.

Note: after creating a project, the project will automatically reference ef4.1

(2) In the model folder, create a 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 (you can also disable it. EF automatically checks and uses SQL Server Express. Here we specify the server and database)

<Connectionstrings>
<! -- <Add name = "studbcontext" connectionstring = "Server = (local); database = mystudent; uid = (Logon account); Pwd = (logon password)" providername = "system. data. sqlclient "/> -->
<Add name = "dataconn" connectionstring = "Server = (local); database = mystudent; uid = (Logon account); Pwd = (logon password)" providername = "system. data. sqlclient "/>
</Connectionstrings>

(5) generate a project to serve the purpose of STEP (6)

(6) Right-click the "controllers" folder and select "add controller".

After you click OK, A studentcontroller class is generated under the controllers folder, and the student sub-folder is generated under the views folder, which contains five. cshtml files,

(7) modify the default route of Global. asax. CS:

Routes. maproute (
"Default", // route name
"{Controller}/{action}/{ID}", // URL with Parameters
New {controller = "student", Action = "Index", id = urlparameter. optional} // default value of the Parameter
);

(8) At last, click the Debug menu, select start debugging, or press f5. to see the following results:

(9) Click the create new hyperlink to add a record to the database.

(10) You can open the database server and find that the mystudent database (corresponding to the database in the connection string) and the studentinfoes table (the plural form of the model class name) are automatically created, the fields in the table correspond to the attributes in the model class respectively. Note that the ID attribute automatically corresponds to the auto-increment primary key column in the table.

 

Note the following:

(1) The connection string in Web. config. providername must be provided; otherwise, an error is returned.

(2) The ID attribute of the model is fixed, or metadata declaration is required. ef4.1 will automatically map it to the table's primary key (auto-increment ).

(3) The context name of the database object is generally the same as the value of the connection string name attribute, but it is different in this article (the context of the database object is studbcontext, and the connection string name is dataconn). If the context name is the same, the object context class does not provide constructors. In this example, you can add constructor to the object context and call the parent class constructor () passing the connection string name different from the object context class name (in this example, dataconn, such as step (2) marked in red)

________________________________________________________________________________________________________________________________________

The following shows the 2nd cases: Create a database mode and then generate a model.

(1) Create the database mystudent on the SQL Server 2005/2008 server and add a table studentinfoes (you can also operate in the server resource manager in)

The table structure is as follows;

(2) create an ASP. NET mvc3/4 Project (use an empty template)

(3) Add the object context class in the models Folder: studbcontext

Public class studbcontext: dbcontext
{
Public studbcontext ()
: Base ("dataconn ")
{
}

Public dbset <studentinfo> students {Get; set ;}
}

(4) Add the entity class: studentinfo to the models folder.

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 ;}
}

(5) configure the connection string in Web. config:

<Connectionstrings>
<! -- <Add name = "studbcontext" connectionstring = "Server = (local); database = mystudent; uid = (Logon account); Pwd = (logon password)" providername = "system. data. sqlclient "/> -->
<Add name = "dataconn" connectionstring = "Server = (local); database = mystudent; uid = (Logon account); Pwd = (logon password)" providername = "system. data. sqlclient "/>
</Connectionstrings>

(6) generate a project solution to serve step (7)

(7) Add the studentcontroller class under the controllers folder,

After you click Add, the same project file structure as in the first scenario is created. As shown above.

(8) modify the route:

Routes. maproute (
"Default", // route name
"{Controller}/{action}/{ID}", // URL with Parameters
New {controller = "student", Action = "Index", id = urlparameter. optional} // default value of the Parameter
);

(9) start debugging. The preview effect is as follows:

 

 

The differences between the two methods are as follows: the Field Types of the automatically generated database table may be different from those of the custom one.

 

Whether you use code to generate a database, create a database, and then create a model, you must understand the ing between them (that is, the role of EF as An ORM framework ), as An ORM framework, ef4.1 follows many conventions, while ASP. net MVC advocates an important principle: conventions come before configuration, which can be said to coincide.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.