简体   繁体   中英

Search DateTime using Entity Framework Core with TempData

I need to search between two dates (From Date, To Date) using entity framework core with TempData, but, until now i phase some problems.

Here is the code for model

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

and the controller code this one

[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");
            }
        }

    }

When I need to export the excel files i found this error:

NullReferenceException: Object reference not set to an instance of an object.

InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expression. To show additional information call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.

My code work like this:

  1. User search put the search criteria (from date, to date, ...)
  2. Then user click search button
  3. After that they can export the search data that he search, because I saved search data in TempData[] dictionary and passed this TempData[] dictionary to ExportExcel FileResult.

How can I solve this problem?

Here is the answer,

First of all:

When you need to read the TempData in Asp.Net Core 3.0 you should read like this TempData["YourDictionaryParameter"] as string not like this TempData["YourDictionaryParameter"].toString()


Now let's see the code that i used to export,

  1. I created this method to handle the search

    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. After I create the search method I applied it to export method

    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; }

After that you will find that export to excel work fine and return what user search correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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