c# - 使用 Entity Framework Core 和 TempData 搜索 DateTime
问题描述
我需要使用带有 TempData 的实体框架核心在两个日期(从日期到日期)之间进行搜索,但是,直到现在我解决了一些问题。
这是模型的代码
[DataType(DataType.DateTime)]
[DisplayName("Activity Log Date Time")]
public DateTime ActivityLogDateTime { get; set; }
和控制器代码这个
[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:对象引用未设置为对象的实例。
InvalidOperationException:尝试计算 LINQ 查询参数表达式时引发异常。要在覆盖 DbContext.OnConfiguring 时显示附加信息,请调用 EnableSensitiveDataLogging()。
我的代码是这样工作的:
- 用户搜索把搜索条件(从日期,到日期,...)
- 然后用户点击搜索按钮
- 之后他们可以导出他搜索的搜索数据,因为我将搜索数据保存在 TempData[] 字典中,并将这个 TempData[] 字典传递给 ExportExcel FileResult。
我怎么解决这个问题?
解决方案
这是答案,
首先:
当您需要阅读 Asp.Net Core 3.0 中的 TempData 时,您应该像这样阅读
TempData["YourDictionaryParameter"] as string
而不是这样阅读TempData["YourDictionaryParameter"].toString()
现在让我们看看我用来导出的代码,
我创建了这个方法来处理搜索
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(); }
创建搜索方法后,我将其应用于导出方法
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 工作正常并正确返回用户搜索的内容。
推荐阅读
- python - 从管道插入时处理 postgress 异常
- linux - bash脚本中的数组长度-1
- multithreading - 为什么我的阻塞期货不能在单核上运行?
- nopcommerce - Trying to Create Order through Order API
- java - Create table as select percentage subquery in Impala DB
- mongodb - mongodb: match, group by multiple fields, project and count
- rest-assured - Can we use io.restassured and jayway in the same method?
- go - How to work with context global variables in Golang?
- apache-flink - Is ConnectedStreams thread safe in Apache Flink
- javascript - What's the meaning of the phrase: String 'wraps around' a string primitive value