Mvc5+ef6 Getting Started complete tutorial Four

Source: Internet
Author: User
Tags actionlink

The previous article focused on how to configure EF, and we reviewed the main process:

Create a data modelà CREATE database Contextà Create Databaseinitializerà configuration entityframework the Context configuration section.

There is still doubt about this process, you can go to the last chapter and then look at it.

This time we will mainly explain (1) EF basic CRUD (2) related to common HtmlHelper

Article outline

Overview & Essentials

Theoretical basis

Detailed steps

Summarize

Overview & Essentials

The following is the main point of this article, the body part will be described in detail.

    • Crud for the EF data model
    • The Common HtmlHelper
    • Repository Pattern
Theoretical basis-EF three programming methods (slightly)

There are a total of three ways:

Database First,model First and code first, we are using code first.

This is a lot of information, I will not repeat, need to understand the three differences and application scenarios please consult other information.

Theoretical basis-EF CRUD

For the previously created Sysuser, Sysrole, sysuserrole Some typical examples, the basic crud people use to imitate these examples.

The database sample data we want to use is as follows:

Sysuser

Sysrole

Sysuserrole

EF data Query

Let's talk about the most frequently used query section.

The EF data query is implemented in LINQ (LINQ to Entities), usually in both expressions and functional styles. It is recommended to use a functional approach, which is relatively simple.

Let's say we've defined the context.

Private Accountcontext db = new Accountcontext ();

    1. [Basic query] query all the Sysuser

var users = from U in db. SysUsers

Select U; Expression style

Users = db. SysUsers; Functional style

    1. [conditional query] Join query criteria

Users = from u in db. SysUsers

where u.username = = "Tom"

Select U; Expression style

Users = db. Sysusers.where (U = u.username = = "Tom"); Functional style

Note that this is the C # notation: "= ="

    1. [Sorting and paging query]

Users = (from u in db. SysUsers

U.username

Select u). Skip (0). Take (5); Expression style

Users = db. Sysusers.orderby (U = u.username). Skip (0). Take (5); Functional style

NOTE only sorted to page out

    1. [Aggregate query]

Total number of user checks

var num = db. Sysusers.count ();

Check Minimum ID

MiniD = db. Sysusers.min (U = u.id);

NOTE Aggregate queries can only be queried by a functional type

    1. [Connection query]

var users = from ur in db. Sysuserroles

Join u in db. SysUsers

On Ur. Sysuserid equals u.id

ur

NOTE

Note that the result returned by the connection query is also a collection of type sysuserroles, with only

The filtering that was made within the connection.

So the question is, if I need to choose a collection, which includes multiple tables, such as sysuser inside the username and sysrole inside the rolename what to do?

This is achieved through the navigation property, the new model in front of the time mentioned, such as Sysuser inside the

Public virtual icollection<sysuserrole> Sysuserroles {get; set;}

But this approach is still not too flexible, and we will say it in the detailed steps below.

EF Data Update

The update step is clearer and looks directly at the code below.

Data updates in three steps: Find objects--Update object data--Save changes

Public ActionResult Efupdatedemo ()

{

1. Find the Object

var sysuser = db. Sysusers.firstordefault (U = u.username = = "Tom");

2. Updating Object data

if (sysuser! = null)

{

Sysuser.username = "Tom2";

}

3. Save changes

Db. SaveChanges ();

return View ();

}

EF Data Add/Remove

Similar to update.

Data additions and deletions

Public ActionResult Efaddordeletedemo ()

{

Add to

1. Create a new entity

var newsysuser = new Sysuser ()

{

UserName = "Scott",

Password = "Tiger",

email = "[Email protected]"

};

2. Increase

Db. Sysusers.add (Newsysuser);

3. Save changes

Db. SaveChanges ();

Delete

1. Find the object you want to delete

var delsysuser = db. Sysusers.firstordefault (U = u.username = = "Scott");

2. Delete

if (delsysuser!=null)

{

Db. Sysusers.remove (Delsysuser);

}

3. Save changes

Db. SaveChanges ();

Return View ("Efquerydemo");

}

Detailed steps
    • Querying the capabilities of users and their respective roles
    • Modify User
    • Add Users and delete users
Querying users and their respective roles
    1. Modify the index method in the controller, add the relevant view, show all users
      1. Pass the model as a parameter

      2. viewsàaccountàindex.cshtml top Add type declaration,

        @model ienumerable<mvcdemo.models.sysuser>

        The body adds a table to display the data

        NOTE

        @Html. ActionLink ("Details", "details", new {id = item.id}) generates a routing address under the same controller.

        Show results

    2. Add a details method that adds the relevant view to show the corresponding user and the corresponding role
      1. Pass a specific model to the past

      2. viewsàaccountàindex.cshtml top Add Enhanced type declaration

        @model MVCDemo.Models.SysUser

        Show the data, and notice how the box section navigates to the information in another table.

        Show results

Update users, add users, delete users

These three operations are similar and belong to the category of updates, which we put together.

    1. Modify Viewsàaccountàindex.cshtml

      Start by adding the Create link.

      Table adds Edit,delete links after each record.

    2. Add the appropriate method to the controller.

      New User:

New user

Public ActionResult Create ()

{

return View ();

}

[HttpPost]

Public ActionResult Create (Sysuser sysuser)

{

Db. Sysusers.add (Sysuser);

Db. SaveChanges ();

Return redirecttoaction ("Index");

}

To modify a user:

Modify User

Public ActionResult Edit (int id)

{

Sysuser sysuser = db. Sysusers.find (ID);

Return View (Sysuser);

}

[HttpPost]

Public ActionResult Edit (Sysuser sysuser)

{

Db. Entry (Sysuser). state = entitystate.modified;

Db. SaveChanges ();

Return redirecttoaction ("Index");

}

To delete a user:

Delete User

Public ActionResult Delete (int id)

{

Sysuser sysuser = db. Sysusers.find (ID);

Return View (Sysuser);

}

[HttpPost, ActionName ("Delete")]

Public ActionResult deleteconfirmed (int id)

{

Sysuser sysuser = db. Sysusers.find (ID);

Db. Sysusers.remove (Sysuser);

Db. SaveChanges ();

Return redirecttoaction ("Index");

}

NOTE

Where data is updated, there are two method overloads with the same name, one for displaying [HttpGet] and one for updating the data [HttpPost]

    1. In the right-click Method name, generate the corresponding view

      Add a declaration to the top of each view

      @model MVCDemo.Models.SysUser

      The specific code in the body of each view:

      Create.cshtml

<body>

<div>

@using (Html.BeginForm ())

{

<div>

@Html. labelfor (model = model. UserName)

@Html. editorfor (model = model. UserName)

</div>

<div>

@Html. labelfor (model = model. Email)

@Html. editorfor (model = model. Email)

</div>

<div>

@Html. labelfor (model = model. Password)

@Html. passwordfor (model = model. Password)

</div>

<div>

<input type= "Submit" value= "Create"/>

</div>

}

<div> @Html. ActionLink ("Back to List", "Index") </div>

</div>

</body>

Edit.cshtml

<body>

<div>

@using (Html.BeginForm ())

{

@Html. hiddenfor (model = model.id)

<div>

@Html. labelfor (model = model. UserName)

@Html. editorfor (model = model. UserName)

</div>

<div>

@Html. labelfor (model = model. Email)

@Html. editorfor (model = model. Email)

</div>

<div>

@Html. labelfor (model = model. Password)

@Html. passwordfor (model = model. Password)

</div>

<div>

<input type= "Submit" value= "Save"/>

</div>

}

<div> @Html. ActionLink ("Back to List", "Index") </div>

</div>

>

Delete.cshtml

<body>

<div>

<dl>

<dt> @Html. displaynamefor (model = model. UserName) </dt>

<dd> @Html. displayfor (model = model. UserName) </dd>

<dt> @Html. displaynamefor (model = model. Email) </dt>

<dd> @Html. displayfor (model = model. Email) </dd>

</dl>

@using (Html.BeginForm ())

{

<div>

<input type= "Submit" value= "Delete"/>

</div>

}

<div>

@Html. ActionLink ("Back to List", "Index")

</div>

</div>

>

NOTE

For the above code, let's mention some of the htmlhelper used here:

Displaynamefor (model=>model.xxx) à generate plain text, display XXX column name

Displayfor (model=>model.xxx) à generates plain text that displays the contents of the XXX column

Lableforà Generate a lable label

Editorforà generates a text type of input

Passwordforà similar to editorfor, hiding text content

Actionlinkà generate a <a> tag

Beginformà Generate a form

NOTE

HtmlHelper is a method that can be called through the Html property of the view (@Html. xxx), can be likened to the original WebForm server-side control, the subsequent article will be divided into several categories, the classification of the introduction, here first simply mention to do a cushion. The best way to learn this is to use a browser to open the appropriate page, view page source, and see the resulting HTML code.

Repository Pattern

It is better to add the repository Pattern, for the next article refactoring code to do a foreshadowing.

Repository pattern is a design pattern, and this concept is certainly often heard.

Definition on "Enterprise Architecture Mode":

Mediates between the domain and data mapping layers using a Collection-like interface for accessing domain objects.

Specific practices:

First, define the interface, define the interface to determine the functional requirements of the data access class, and then implement the interface.

Take an example of the operation of the Sysuser table.

Build a folder repositories, create a new interface in the folder Isysuserrepository

We define several features in advance.

Namespace Mvcdemo.repositories

{

public interface Isysuserrepository

{

Query All Users

Iqueryable<sysuser> SelectAll ();

Querying users by user name

Sysuser selectbyname (string userName);

Add user

void Add (Sysuser sysuser);

Delete User

BOOL Delete (int id);

}

}

Create a new class under the same folder, inherit the interface, and implement the function.

Namespace Mvcdemo.repositories

{

public class Sysuserrepository:isysuserrepository

{

Protected Accountcontext db = new Accountcontext ();

Query All Users

Public iqueryable<sysuser> SelectAll ()

{

Return DB. SysUsers;

}

Querying users by user name

Public Sysuser Selectbyname (string userName)

{

Return DB. Sysusers.firstordefault (U = u.username = = UserName);

}

Add user

public void Add (Sysuser sysuser)

{

Db. Sysusers.add (Sysuser);

Db. SaveChanges ();

}

Delete User

public bool Delete (int id)

{

var delsysuser=db. Sysusers.firstordefault (U = u.id = = ID);

if (delsysuser! = null)

{

Db. Sysusers.remove (Delsysuser);

Db. SaveChanges ();

return true;

}

Else

{

return false;

}

}

}

}

Invoking an instance of the Sysuserrepository class through the Isysuserrepository interface object:

Isysuserrepository ur=new sysuserrepository ();

var user=ur.xxx;

How, usually hears the repository pattern realizes to be so simple.

The landlord hint design pattern all originates from the programming practice, as long as grasps several important principles, GOF summarizes the design pattern to be able to deduce itself, is similar to the geometrical axiom and the theorem relations. Everyone in the work to do a conscientious, more thinking, more summary.

Summarize

OK, so far, we've introduced the common crud. View, the controller interacts between the controllers by passing the model. In particular, to mention the following diagram, through the navigation property implementation of Sysuseràsysuserroleàsysrole Multi-table query.

Of course, this approach is still limited, in the following article we will describe how to implement similar to the previous SQL query multiple tables, the query results of multiple tables, such as a DataTable directly into view to display data.

All right, here we go today.

Welcome everyone to comment, let the next article better:)

Mvc5+ef6 Getting Started complete tutorial Four

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.