【EntityFrame使用】数据库常用curd方式

一.插入数据

 LicenceCabEntities db = new LicenceCabEntities();
            Log log = db.Logs.CreateObject();
            log.Action = action;
            log.File = mediaPath;
            log.Info = info;
            log.User = user;
            log.Time = DateTime.Now;
            db.Logs.AddObject(log);
            db.SaveChanges();

二.修改数据

1.查询到记录后重新赋值然后保存刷新

var users = Context.Db.Users.Where(u => u.Id == user.User.Id).ToList();
            if (users.Count != 1) return;

            users[0].Password = pwd;
            Context.Db.SaveChanges();
            Context.Db.Refresh(RefreshMode.StoreWins, Context.Db.Users);

2.SQL语句方式

Context.Db.ExecuteStoreCommand("update Tasks set State='1' where TaskNo='" + strNo + "'");

三.删除数据

1.var o = c.book.FirstOrDefault(s => s.BookCode == "007");
               c.book.DeleteObject(o);
               c.SaveChanges();

2.SQL语句方式

四.查询数据

1.where\FirstOrDefault\tolist等查询返回方法

dv1.DataSource = Context.Db.Logs.Where(l => EntityFunctions.DiffDays(l.Time, dpRecDate.Value) <= 0 && EntityFunctions.DiffDays(l.Time, dpRecDateSec.Value) >= 0).OrderByDescending(l => l.Time);

2.查询视图

dv2.DataSource=Context.Db.ExecuteStoreQuery("select * from TaskInfoView where TaskNo='" + strTaskNo + "'");

3.语句查询

Context.Db.SqlQuery("select * from [T_EF] where [ID] = {0}", 2);

五.事务

 

using (TransactionScope transaction = new TransactionScope())
{
try
{
    string sql = “”;
    string sql2 = “”";
    var result1 = tc.Database.ExecuteSqlCommand(sql) > 0 ? true : false;
    var result2 = tc.Database.ExecuteSqlCommand(sql2) > 0 ? true : false;

    if (result1 && result2)
    {
        transaction.Complete();
    }
}
catch (Exception ex)
{

    return Json(new { result = "1", message = "更新失败! "+ex });
}

}

你可能感兴趣的:(数据库,编程基础)