EF Getting Started-crud action

Source: Internet
Author: User

One, EF data query
Let's say we've defined the context:
Private Accountcontext db = new Accountcontext ();

1, [basic query] query all
var users = from U in db. SysUsers
Select U;

Users = db. SysUsers;

2, [conditional query] Join the query conditions
Users = from u in db. SysUsers
where u.username = = "Tom"
Select U;

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

3, [Sorting and paging query]
Users = (from u in db. SysUsers
U.username
Select u). Skip (0). Take (5);

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

Note: Only sorted to page out

4. [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 function

5. [Connection query]
var users = from ur in db. Sysuserroles
Join u in db. SysUsers
On Ur. Sysuserid equals u.id
Select ur

Second, EF data Update
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 ();
}

Third, EF Data Add/Remove
Similar to update.
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");
}

EF Getting Started-crud action

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.