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