Entity framework query, EF execution sql

Source: Internet
Author: User

First, Introduction

EF supports the open bottom of the ADO framework, DbContext has three common methods

Dbset.sqlquery//Queries and returns entitiesdbcontext.database.sqlquery<t>     //Executes a query, and can convert the return set to an object Dbcont Ext. Database.executesqlcommand    //execute a SQL command with no return set, such as Update,delete operation  
Second, usage

1. Dbset.sqlquery usage

            var list = db.admins.SqlQuery ("SELECT * from admin");            foreach (var item in list)            {                Response.Write (item.username);                Response.Write ("<br>");            }  

2. Dbcontext.database.sqlquery<t> usage

            var list = db. Database.sqlquery<admin> ("SELECT * from admin"). ToList ();            foreach (var item in list)            {                Response.Write (item.username);                Response.Write ("<br>");            }  

3. DbContext.Database.ExecuteSqlCommand Usage

var res=db. Database.executesqlcommand ("Update admin set password= ' 123456 '");            Response.Write (res);

Description:results of 1 and 2 are the same

Iii. Summary

Native SQL execution Query:

Need to return entity model, use Dbset.sqlquery (context Trace, equivalent to LINQ mode)

Need to return other types, using Database.sqlquery

Native SQL to perform the update:

Using Database.executesqlcommand

Iv. examples of common queries

1, EF Select how to get the last 10 days of data

DateTime now = DateTime.Now; var res = db. News.where (p = System.Data.Objects.EntityFunctions.DiffDays (DateTime.Now, P.createtime) <), return Res. Tolist<news> (); 

2. Load ...

Entity framework query, EF execution sql

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.