繁体   English   中英

使用 Entity Framework Core 和 TempData 搜索 DateTime

[英]Search DateTime using Entity Framework Core with TempData

我需要使用带有 TempData 的实体框架核心在两个日期(从日期到日期)之间进行搜索,但是,直到现在我解决了一些问题。

这是 model 的代码

[DataType(DataType.DateTime)]
    [DisplayName("Activity Log Date Time")]
    public DateTime ActivityLogDateTime { get; set; }

和 controller 代码这个

[HttpPost(Name = "Index")]
    public async Task<IActionResult> Index(int? page, DateTime fromDate, DateTime toDate, string operation, string userName, string pageName, string number)
    {
        //Viewbag information for view
        ViewBag.fromDate = fromDate;
        ViewBag.toDate = toDate;
        ViewBag.operation = operation;
        ViewBag.userName = userName;
        ViewBag.pageName = pageName;

        //To store search data
        TempData["fromDate"] = fromDate;
        TempData["toDate"] = toDate;
        TempData["operation"] = operation;
        TempData["userName"] = userName;
        TempData["pageName"] = pageName;

        //Check if number == null then put default value 10
        if (number == null)
        {
            number = "10";
        }


        //Record Activity Logs
        activity.PageId = 1;
        var name = await db.Pages.FindAsync(activity.PageId);
        activity.Username = User.Identity.Name;
        activity.Operation = "Search";
        activity.Description = "Username: (" + User.Identity.Name + ") search in page number " + activity.PageId.ToString() + " (" + name.PageName + ")";
        activity.TechnicalDescription = "Username = " + User.Identity.Name + ", PageId = " + activity.PageId.ToString() + ", fromDate = " + fromDate
            + ", toDate = " + toDate + ", operation = " + operation + ", username = " + userName + ", pagename = " + pageName;
        activity.ActivityLogDateTime = DateTime.Now;
        //End Record Activity Logs

        db.ActivityLogs.Add(activity);
        await db.SaveChangesAsync();


        if (fromDate.Year.ToString().Equals("1") && toDate.Year.ToString().Equals("1") && operation == null && userName == null && pageName == null) 
        {
            return View(await db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).ToPagedListAsync(page ?? 1, 10));
        }
        else
        {
            return View(await db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime)
            .Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && string.IsNullOrEmpty(operation) ? true : x.Operation.Contains(operation)
            && string.IsNullOrEmpty(userName) ? true : x.Username.Contains(userName) && string.IsNullOrEmpty(pageName) ? true : x.Pages.PageName.Contains(pageName))
            .ToPagedListAsync(page ?? 1, int.Parse(number)));
        }

    }

public FileResult ExportExcel()
    {
        DataTable dt = new DataTable("Grid");
        dt.Columns.AddRange(new DataColumn[7] { new DataColumn("Activity Logs Id"),
                                        new DataColumn("Date and Time"),
                                        new DataColumn("Username"),
                                        new DataColumn("Operation"),
                                        new DataColumn("Description"),
                                        new DataColumn("Technical Description"),
                                        new DataColumn("PageName")});

        var report = new List<ActivityLogs>();

        if (Convert.ToDateTime(TempData["fromDate"].ToString()).Year.ToString().Equals("1") && Convert.ToDateTime(TempData["toDate"]).Year.ToString().Equals("1") 
            && TempData["operation"].ToString() == null && TempData["userName"].ToString() == null && TempData["pageName"].ToString() == null)
        {
            report = db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).ToList();
        }
        else
        {
            report = db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime)
            .Where(x => x.ActivityLogDateTime >= Convert.ToDateTime(TempData["fromDate"].ToString()) && x.ActivityLogDateTime <= Convert.ToDateTime(TempData["toDate"].ToString())
            && string.IsNullOrEmpty(TempData["operation"].ToString()) ? true : x.Operation.Contains(TempData["operation"].ToString())
            && string.IsNullOrEmpty(TempData["userName"].ToString()) ? true : x.Username.Contains(TempData["userName"].ToString()) 
            && string.IsNullOrEmpty(TempData["pageName"].ToString()) ? true : x.Pages.PageName.Contains(TempData["pageName"].ToString())).ToList();
        }


        foreach (var item in report)
        {
            dt.Rows.Add(item.ActivityLogId, item.ActivityLogDateTime, item.Username, item.Operation, item.Description, item.TechnicalDescription,
                item.Pages.PageName);
        }

        using (XLWorkbook wb = new XLWorkbook())
        {
            wb.Worksheets.Add(dt);
            using (MemoryStream stream = new MemoryStream())
            {
                wb.SaveAs(stream);
                return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ActivityLogs " + DateTime.Now +".xlsx");
            }
        }

    }

当我需要导出 excel 文件时,我发现了这个错误:

NullReferenceException: Object 引用未设置为 object 的实例。

InvalidOperationException:尝试评估 LINQ 查询参数表达式时引发异常。 要在覆盖 DbContext.OnConfiguring 时显示附加信息,请调用 EnableSensitiveDataLogging()。

我的代码是这样工作的:

  1. 用户搜索把搜索条件(从日期,到日期,...)
  2. 然后用户点击搜索按钮
  3. 之后他们可以导出他搜索的搜索数据,因为我将搜索数据保存在 TempData[] 字典中,并将这个 TempData[] 字典传递给 ExportExcel FileResult。

我怎么解决这个问题?

这是答案,

首先:

当您需要在 Asp.Net Core 3.0 中读取 TempData 时,您应该像这样读取TempData["YourDictionaryParameter"] as string而不是像这样TempData["YourDictionaryParameter"].toString()


现在让我们看看我用来导出的代码,

  1. 我创建了这个方法来处理搜索

    private List<ActivityLogs> GetSearchResult() { DateTime fromDate = Convert.ToDateTime(TempData["fromDate"].ToString()); DateTime toDate = Convert.ToDateTime(TempData["toDate"].ToString()); string operation = TempData["operation"] as string; string userName = TempData["userName"] as string; string pageName = TempData["pageName"] as string; TempData.Keep(); if (fromDate == default(DateTime) && toDate == default(DateTime)) { if (operation == null && userName == null && pageName == null) { return db.ActivityLogs.Include(x => x.Pages).ToList(); } } else { if (operation.= null && userName == null && pageName == null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && x.Operation.Contains(operation));ToList(). } else if (operation == null && userName.= null && pageName == null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && x.Username;Contains(userName)).ToList(). } else if (operation == null & userName == null && pageName.= null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && x.Pages;PageName.Contains(userName)).ToList(). } else if (operation.= null && userName.= null && pageName == null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && x;Username.Contains(operation) && x.Username.Contains(userName)).ToList(). } else if (operation.= null && userName == null && pageName.= null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x;ActivityLogDateTime <= toDate && x.Operation.Contains(operation) && x.Pages.PageName.Contains(pageName)).ToList(). } else if (operation == null && userName.= null && pageName.= null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x.ActivityLogDateTime);Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && x.Username.Contains(userName) && x.Pages.PageName.Contains(pageName)).ToList(). } else if (operation.= null && userName.= null && pageName.= null) { return db.ActivityLogs.Include(x => x.Pages).OrderByDescending(x => x;ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate && x.Operation.Contains(operation) && x.Username.Contains(userName) && x.Pages.PageName;Contains(pageName)).ToList(). } else if(operation == null && userName == null && pageName == null) { return db.ActivityLogs.Include(x => x;Pages).OrderByDescending(x => x.ActivityLogDateTime).Where(x => x.ActivityLogDateTime >= fromDate && x.ActivityLogDateTime <= toDate).ToList(); } } return db.ActivityLogs.OrderByDescending(x => x.ActivityLogDateTime).ToList(); }
  2. 创建搜索方法后,我将其应用于导出方法

    public async Task<IActionResult> ExportPDF() { var activityLogs = await new List<ActivityLogs>().ToListAsync(); activityLogs = GetSearchResult(); var report = new ViewAsPdf("ActivityLogsReport", activityLogs) { PageMargins = { Left = 20, Bottom = 10, Right = 20, Top = 10 }, FileName = "ActivityLogs " + DateTime.Now + ".pdf", PageSize = Rotativa.AspNetCore.Options.Size.A4, PageOrientation = Rotativa.AspNetCore.Options.Orientation.Portrait, //CustomSwitches = "--page-offset 0 --footer-center [page] --footer-font-size 12" CustomSwitches = "--footer-center \" Created Date: " + DateTime.Now.Date.ToString("dd/MM/yyyy") + " Page: [page]/[toPage]\"" + " --footer-line --footer-font-size \"12\" --footer-spacing 1 --footer-font-name \"Segoe UI\"" }; return report; }

之后,您会发现导出到 excel 可以正常工作并正确返回用户搜索的内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM