码迷,mamicode.com
首页 > 数据库 > 详细

【EF学习笔记03】----------使用原生Sql语句

时间:2016-08-09 09:28:05      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:

在EF中使用原生SQL,首先要创建上下文对象

using (var db = new Entities())
{
    //数据操作
}

新增

string sql = "insert into UserInfo values(‘zhangsan‘,‘123456‘)";
    db.Database.ExecuteSqlCommand(sql);

参数化新增

    sql = "insert into UserInfo values(@UserName,@UserPass)";
    var param = new SqlParameter[] 
    {
        new SqlParameter("@UserName","lisi"),
        new SqlParameter("@UserPass","123456")
    };
    db.Database.ExecuteSqlCommand(sql, param);

删除

    sql = "delete from UserInfo where UserName=‘zhangsan‘";
    db.Database.ExecuteSqlCommand(sql);

参数化删除

    sql = "delete from UserInfo where UserName=@UserName";
    db.Database.ExecuteSqlCommand(sql, new SqlParameter("@UserName", "lisi"));

修改

    sql = "update UserInfo set UserName=‘wangwu‘";
    db.Database.ExecuteSqlCommand(sql);

查询多条记录

    sql = "select * from UserInfo";
    var users = db.Database.SqlQuery<UserInfo>(sql);
    foreach (var user in users)
    {
        ObjectDumper.Write(user);//打印对象
    }

总结:操作方式与ADO.NET类似,EF框架自动为我们封装了数据库链接和查询对象。

 

完整案例:

//1.创建上下文对象
            using (var db = new Entities())
            {
                //
                string sql = "insert into UserInfo values(‘zhangsan‘,‘123456‘)";
                db.Database.ExecuteSqlCommand(sql);

                //参数化新增
                sql = "insert into UserInfo values(@UserName,@UserPass)";
                var param = new SqlParameter[] 
                {
                    new SqlParameter("@UserName","lisi"),
                    new SqlParameter("@UserPass","123456")
                };
                db.Database.ExecuteSqlCommand(sql, param);

                //
                sql = "delete from UserInfo where UserName=‘zhangsan‘";
                db.Database.ExecuteSqlCommand(sql);

                //参数化删除
                sql = "delete from UserInfo where UserName=@UserName";
                db.Database.ExecuteSqlCommand(sql, new SqlParameter("@UserName", "lisi"));

                //
                sql = "update UserInfo set UserName=‘wangwu‘";
                db.Database.ExecuteSqlCommand(sql);

                //原生sql查询
                sql = "select * from UserInfo";
                var users = db.Database.SqlQuery<UserInfo>(sql);
                foreach (var user in users)
                {
                    ObjectDumper.Write(user);//打印对象
                }
            }

 

【EF学习笔记03】----------使用原生Sql语句

标签:

原文地址:http://www.cnblogs.com/gosky/p/5751740.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!