使用c#获取数据在ASP.net中输入数据库的时间

问题描述 投票:0回答:1

我想找到数据输入数据库的时间。我正在使用SQL Server作为我的数据库。

public class OtpchangeController : Controller
{
    DateTime dbTime;
    // GET: Otpchange
    public ActionResult Generateotp()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Generateotp(tblPassword obj)
    {
        Random r = new Random();
        using (PasswordGenerationEntities db = new PasswordGenerationEntities())
        {
            tblPassword newObj = (from c in db.tblPasswords
                                  where c.Username == obj.Username
                                  select c).First();
            if(newObj != null)
            {
                int num = r.Next();
                string newOtp = num.ToString();
                newObj.Otp = newOtp;
                db.SaveChanges();
                dbTime = DateTime.Now;
                Session["Username"] = newObj.Username.ToString();
                return RedirectToAction("ChangePassword");
            }
        }
        return View();
    }
    public ActionResult ChangePassword()
    {
        return View();
    }
    [HttpPost]
    public ActionResult ChangePassword(tblPassword obj)
    {
        string name = @Session["Username"].ToString();
        using (PasswordGenerationEntities db = new PasswordGenerationEntities())
        {

            tblPassword newObj = (from c in db.tblPasswords
                                  where c.Otp == obj.Otp && c.Username == name
                                  select c).First();
            DateTime formTime = DateTime.Now;
            TimeSpan result = dbTime.Subtract(formTime);
            newObj.Password = obj.Password;
            db.SaveChanges();
            return RedirectToAction("Success");
        }
        //return View();
    }
    public ActionResult Success()
    {
        return View();
    }

在这里,我想找出otp添加到数据库的时间与用户输入otp的时间之间的差异。

但dbTime来自01/01/2001

formTime是正确的,我也希望找到那些时间之间的差异。

c# asp.net asp.net-mvc
1个回答
0
投票

您提供的代码似乎没有编译或缺少某些部分。

无论如何说我会建议检查有关dbContext及其功能here的msdn文档

您可以将数据库日志委派给控制台日志或其他更合适的提供程序(log4net或简单的自定义日志文件)。这些日志包含有关数据库执行时间的信息

在你的情况下,你可以这样做:

    using (PasswordGenerationEntities db = new PasswordGenerationEntities())
    {
        db.Database.Log = Console.Write; 
        tblPassword newObj = (from c in db.tblPasswords
                              where c.Username == obj.Username
                              select c).First();
        if(newObj != null)
        {
            int num = r.Next();
            string newOtp = num.ToString();
            newObj.Otp = newOtp;
            db.SaveChanges();
            dbTime = DateTime.Now;
            Session["Username"] = newObj.Username.ToString();
            return RedirectToAction("ChangePassword");
        }
    }

检查控制台输出。

Console Database info

© www.soinside.com 2019 - 2024. All rights reserved.