這裏主要介紹兩種查詢方法 Linq to entity(L2E)和Sqlhtml
L2E查詢時能夠使用linq query語法,或者lambda表達式,默認返回的類型是IQueryable,(linq查詢默認返回的是IEnumerable),下邊給出了一個簡單的例子sql
//查詢名字爲ls的用戶集合 //query語法 var users = from u in context.UserInfo where u.UserName == "ls" select u; //method語法 var users2 = context.UserInfo.Where<UserInfo>(user => user.UserName == "ls");
linq的使用方法詳見linq總結系列(一)---基礎部分,其中的CRUD操做都是使用linq的語法,這裏就很少囉嗦了~數據庫
返回的結果是DbSqlQuery類型,該類型實現了IEnumberable接口,因此結果集也能夠用linq操做post
//查詢名字爲ls,密碼是123321的用戶集 //使用佔位符,執行的時候自動生成sql參數,不用擔憂sql注入 var user1 = context.UserInfo.SqlQuery("select * from userinfo where username=@p0 and userpass=@p1", "ls", "123"); //本身設sql參數 SqlParameter [] pars= { new SqlParameter("@name", SqlDbType.NVarChar, 20) { Value = "ls" }, new SqlParameter("@pass", SqlDbType.NVarChar, 20) { Value="123"} }; var user2 = context.Database.SqlQuery<UserInfo>( "select * from userinfo where username=@name and userpass=@pass", pars); //查詢用戶人數 int count = context.Database.SqlQuery<int>("select count(*) from userinfo").SingleOrDefault();
context.Database對應着底層數據庫,Database.SqlQuery用於查詢,能夠返回任意類型。spa
using (var ctx = new SchoolDBEntities()) { //獲取ID爲1的student的名字 string studentName = ctx.Database.SqlQuery<string>("Select studentname from Student where studentid=@id", new SqlParameter("@id", 1)) .FirstOrDefault(); }
Database.ExecuteSqlCommand()用於經過Sql進行CUD操做,返回int類型(受影響的行數)code
using (var ctx = new SchoolDBEntities()) { //修改 int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student set studentname ='changed student by command' where studentid=@id", new SqlParameter("@id", 1)); //添加 int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname) values('New Student')"); //刪除 int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student where studentid=@id",new SqlParameter("@id", 1));
}
EF系列目錄連接:Entity Franmework系列教程彙總htm