原文:我的EntityFramework(2):简单的数据查询
在上一篇博文中,已经搭建了基本的框架,接下来就进行简单的数据查询,这里主要用了Linq
常见的数据集查询
var companyList = from c in dbs.Company where c.ID > 417154 orderby c.CompanyName descending select new { c.ID, c.CompanyName, c.Email, c.HtmlUrl }; gvList.DataSource = companyList.ToList();//类型转换 gvList.DataBind();
拼接SQL字符串执行查询
using (var dbs = new Movie_DBEntities1()) { string sql = "select [Title] from Movie"; var objList2 = dbs.Database.SqlQuery<string>(sql);//此语句,仅支持单列多行的查询 foreach (var item in objList2) { Response.Write(item + "<br>"); } }
下面属于转载的
EF中使用语句 或存储过程 查询
1、无参数查询
var model = db.Database.SqlQuery<UserInfo>("select* from UserInfoes ").ToList();
2、有参查询
var model = db.Database.SqlQuery<UserInfo>("select* from UserInfoes where [email protected] ",new SqlParameter("@ID",id)).ToList();
3、结合linq查询
var model = (from p in db.userinfo.SqlQuery("select * from UserInfoes where [email protected]",new SqlParameter("@ID", 1)) select p).ToList();
4:EF原始查询单独表
model = db.userinfo.OrderByDescending(a => a.ID).Skip(10 * (当前页 - 1)).Take(10).ToList();
5,EF 执行存储过程或delete 删除语句
SqlParameter[] para = new SqlParameter[] {
new SqlParameter("@ID",id)
};
db.Database.ExecuteSqlCommand("delete UserInfoes where [email protected]", para);
存储过程 删除,有几个参数,存储后面要带几个参数以逗号分隔
SqlParameter[] para = new SqlParameter[] {
new SqlParameter("@ID",id)
};
db.Database.ExecuteSqlCommand("sp_Userinfos_deleteByID @ID", para);