我正在开发一个应用程序,该应用程序根据用户在表单中选择的选项生成“报告” View 。由于我根据用户输入“动态”生成必要的数据库查询,因此我选择使用原始 SQL,而不是 LINQ 查询。
[HttpPost]
public ActionResult GeneratedReport(String StartDate, String EndDate, String EquipmentID, String LocationID, String UserID )
{
String sqlQuery = String.Format("SELECT * from Records WHERE RecordDate BETWEEN '{0}' and '{1}'", StartDate, EndDate);
GeneratedReportViewModel vm = new GeneratedReportViewModel();
List<Record> records;
bool userFilter = (UserID == "") ? false : true;
bool locationFilter = (LocationID == "") ? false : true;
bool equipmentFilter = (EquipmentID == "") ? false : true;
if(userFilter) {
sqlQuery += " AND UserID = " + UserID;
} if(locationFilter) {
sqlQuery += " AND LocationID = " + LocationID;
} if(equipmentFilter) {
sqlQuery += " AND EquipmentID = " + EquipmentID;
}
records = dbContext.Database.SqlQuery<Record>(sqlQuery).ToList();
vm.FilteredRecords = records;
return View("GeneratedReport", vm);
}
}
实体生成的Record类的定义:
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.Spatial;
public partial class Record
{
public int RecordID { get; set; }
public DateTime RecordDate { get; set; }
public int EquipmentID { get; set; }
public int ActionTypeID { get; set; }
public int UserID { get; set; }
[StringLength(200)]
public string Notes { get; set; }
public int LocationID { get; set; }
public virtual Action Action { get; set; }
public virtual Equipment Equipment { get; set; }
public virtual Location Location { get; set; }
public virtual User User { get; set; }
}
}
但是,每当服务器尝试加载与GenerateReport 关联的 View (代码如下)时,Record 对象的所有导航属性(用户、位置、设备、操作)都为空。
@model IT_Equipment_Log.ViewModels.GeneratedReportViewModel
@{
ViewBag.Title = "GeneratedReport";
}
<table>
<tr><th>Equipment</th><th>User</th><th>Date</th><th>Location</th><th>Action</th><th>Notes</th></tr>
@foreach (var record in @Model.FilteredRecords)
{
<tr><td>@record.Equipment.SerialNumber</td><td>@record.User.FullName</td><td>@record.RecordDate</td><td>@record.Location.DisplayName</td><td>@record.Action.Description</td><td>@record.Notes</td></tr>
}
</table>
我不知道如何使 Include() 在这种情况下工作,也不知道如何将此 SQL 语句(因为它会根据用户输入而变化)转换为 LINQ 查询。是否还有其他可用选项,或者我如何解决此问题?
非常感谢。
最佳答案
我尝试使用 LINQ 重写您的代码。猜测它会获得您想要的导航属性。
var records = dbContext.Record.Where(p => p.RecordDate >= StartDate && p.RecordDate <= EndDate);
if(!string.IsNullOrEmpty(UserID)){
records.Where(p => p.UserID = UserID);
}
if(!string.IsNullOrEmpty(LocationID)){
records.Where(p => p.LocationID = LocationID);
}
if(!string.IsNullOrEmpty(EquipmentID)){
records.Where(p => p.EquipmentID = EquipmentID);
}
var vm = vm = new GeneratedReportViewModel{
FilteredRecords = records
};
return View("GeneratedReport", vm);
关于c# - ASP.NET MVC 和实体 - 使用原始 SQL 时加载导航属性/对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41398653/