Use efcodefirst 1.0 in ASP. NET mvc3

Source: Internet
Author: User
1. Create a project

Open vs2010, select File> New> Project, and create an ASP. NET mvc3 web application.ProgramHere, I name it blog.

2. Compile entity classes

For a blog, several classes should be required:

    • Post blogArticleClass
    • Comment comments and post are one-to-many relationships
    • CATEGORY Directory class, which has one-to-many relationship with post
    • Tag tag class, which is a many-to-many relationship with post
    • Friendlink links

Do not consider anything like the administrator. Add the above classes in sequence in the model.

01
Namespace Blog. Models

02
{

03
Public Class Post

04
{

05
Public Int Id {Get;Set;}

06
Public Int Categoryid {Get;Set;}

07

08
Public String Title {Get;Set;}

09
Public String Summary {Get;Set;}

10
Public String Alias {Get;Set;}

11
Public String Content {Get;Set;}

12
Public Datetime createtime {Get;Set;}

13

14
Public CATEGORY category {Get;Set;}

15
Public Icollection <tag> tags {Get;Set;}

16
Public Icollection <comment> coments {Get;Set;}

17
}

18
}

01
Namespace Blog. Models

02
{

03
Public Class Comment

04
{

05
Public Int Id {Get;Set;}

06
Public Int Postid {Get;Set;}

07
Public Int Level {Get;Set;}

08
Public Int Replyto {Get;Set;}

09

10
Public String Username {Get;Set;}

11
Public String Email {Get;Set;}

12
Public String Website {Get;Set;}

13
Public String Content {Get;Set;}

14
Public Datetime createtime {Get;Set;}

15

16
}

17
}

01
Namespace Blog. Models

02
{

03
Public Class Category

04
{

05
Public Int Id {Get;Set;}

06

07
Public String Name {Get;Set;}

08
Public String Alias {Get;Set;}

09
Public String Description {Get;Set;}

10
Public Datetime createtime {Get;Set;}

11

12
Public Icollection <post> posts {Get;Set;}

13
}

14
}

01
Namespace Blog. Models

02
{

03
Public Class Tag

04
{

05
Public Int Id {Get;Set;}

06

07
Public String Name {Get;Set;}

08
Public String Alias {Get;Set;}

09
Public Datetime createtime {Get;Set;}

10

11
Public Icollection <post> posts {Get;Set;}

12
}

13
}

01
Namespace Blog. Models

02
{

03
Public Class Friendlink

04
{

05
Public Int Id {Get;Set;}

06

07
Public String Name {Get;Set;}

08
Public String URL {Get;Set;}

09
Public String Description {Get;Set;}

10
Public Datetime createtime {Get;Set;}

11
}

12
}

3. Add efcodefirst

Choose tools> library package magager> Package Manager Console

On the Package Manager Console, enter the following command to install efcodefirst:

1
PM>Install-Package efcodefirst

After the installation is successful, vs automatically adds a reference to the entityframework in your project.

4. Configuration

The configuration of efcodefirst is quite simple. We add the blogdb class to the model.

01
Using System. Data. entity;

02

03
Namespace Blog. Models

04
{

05
Public Class Blogdb: dbcontext

06
{

07
Public Dbset <post> posts {Get;Set;}

08
Public Dbset <tag> tags {Get;Set;}

09
Public Dbset <Category> categories {Get;Set;}

10
Public Dbset <comment> comments {Get;Set;}

11
Public Dbset <friendlink> friendlinks {Get;Set;}

12
}

13
}

Open the Web. config file and add a link string

01
<Connectionstrings>

02
<Add Name="Blogdb"

03
Connectionstring = "Server = .\;

04
Database=Blog;Trusted_connection=True"

05
Providername="System. Data. sqlclient" />

06
<! -- <Add name = "blogdb"

07
Connectionstring = "Server =. \ express;

08
Database = blog; trusted_connection = true"

09
Providername = "system. Data. sqlclient"/> -->

10
</Connectionstrings>

Note that the value of the name attribute is "blogdb", which is consistent with the Class Name of the blogdb class. The database name is blog (this database does not exist now ).

5. Test the knife

Create a homecontroller and add the followingCode.

01
Using Blog. models;

02

03
Namespace Blog. Controllers

04
{

05
Public Class Homecontroller: Controller

06
{

07
Blogdb _ DB =New Blogdb ();

08
//

09
// Get:/home/

10

11
Public Actionresult index ()

12
{

13
VaR posts = _ dB. posts;

14
Return View (posts );

15
}

16

17
}

18
}

Create a view for index action, as shown in:

After adding it, you can't wait to press F5 decisively. Let's see what happened!

The following information is displayed on the webpage, but this is not the focus of today. Today, the focus is on databases. Let's open the database and see what happened in it.

Look, EF automatically creates a database for us.

In addition, EF is smart enough to complete the many-to-many relationship between posts and tags !!! In our program, there is no model corresponding to the tagposts table, and some are just the following two lines of code:

In the post class

1
Public Icollection <tag> tags {Get;Set;}

In the tag class

1
Public Icollection <post> posts {Get;Set;}

We can use the following code to obtain all the articles in the label "CSHARP.

1
VaR posts = _ dB. tags

2
. Where (t => T. Name ="CSHARP")

3
. Single ()

4
. Posts;

6. After the model is modified, the data table is automatically updated.

When we modify the model and run the website, an error is reported because EF cannot match the updated model with the old data table. In order to make the database updated with the model, we need to do the following.

Open the global. asax file in the root directory

Add the following namespace (Note: efcodefirst 1.0 and 0.8 have different namespaces for the database class)

1
Using System. Data. entity;

2
Using Blog. models;

Create a new blogdbinitializer class to inherit dropcreatedatabaseifmodelchanges <blogdb> and rewrite the seed function.

01
Public Class Blogdbinitializer

02
: Dropcreatedatabaseifmodelchanges <blogdb>

03
{

04
Protected Override Void Seed (blogdb context)

05
{

06
Base. Seed (context );

07

08
VaR links =New List <friendlink>

09
{

10
New Friendlink {

11
Name ="Ninofocus.com",

12
Url =@ Http://ninofocus.com",

13
Description ="Ninofocus's personal blog"

14
},

15
New Friendlink {

16
Name ="Ninofocus at cnblogs",

17
Url =@ Http://www.cnblogs.com/nizhuguo",

18
Description ="Ninofocus blog in the blog Park"

19
}

20
};

21
Links. foreach (L => context. friendlinks. Add (l ));

22
Context. savechanges ();

23
}

24
}

Add the following code to application_start ():

After each database reconstruction, the data in the database is cleared. The role of the seed () function is to add the following initialization data to the new database.

I added two links to the code above.

7. Write at the end

I have just learned the EF framework, and I haven't noticed it in many places, or I am wrong. Please give me some advice!

Source code download

Blog.rar

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.