查询List <string>中选定字段的所有数据的数据库表?

我正在为我的MVC5 Code-First应用程序添加Export()function。 为此,我创build了以下ViewModelExportAssetsViewModel

 public class ExportAssetsViewModel { public Dictionary<int, string> ListOfExportFields { get; set; } public int[] SelectedFields { get; set; } public ExportAssetsViewModel() { ListOfExportFields = new Dictionary<int, string>() { {1, "Model"}, {2, "Manufacturer"}, {3, "Type"}, {4, "Location"}, {5, "Vendor"}, {6, "Status"}, {7, "ip_address"}, {8, "mac_address"}, {9, "note"}, {10, "owner"}, {11, "cost"}, {12, "po_number"}, {13, "description"}, {14, "invoice_number"}, {15, "serial_number"}, {16, "asset_tag_number"}, {17, "acquired_date"}, {18, "disposed_date"}, {19, "verified_date"}, {20, "created_date"}, {21, "created_by"}, {22, "modified_date"}, {23, "modified_by"}, }; } } 

这是用来显示我的MultiSelectList在我的ExportController - Index()视图:

ExportController – Index()操作

  public ActionResult Index() { ExportAssetsViewModel expViewMod = new ExportAssetsViewModel(); return View(expViewMod); } 

索引视图

 @model InventoryTracker.Models.ExportAssetsViewModel @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Export</h2> <p>Please select which Asset fields to Export to Excel:</p> @using (Html.BeginForm("ExportUsingEPPlus", "Export", FormMethod.Post)) { @Html.ListBoxFor(m => m.SelectedFields, new MultiSelectList(Model.ListOfExportFields, "Key", "Value"), new { @class = "form-control", style = "height: 250px;" }) <br /> <input type="submit" value="ExportUsingEPPlus" /> } 

索引视图 – 渲染的HTML

 <h2>Export</h2> <p>Please select which Asset fields to Export to Excel:</p> <form action="/Export/ExportUsingEPPlus" method="post"><select class="form-control" id="SelectedFields" multiple="multiple" name="SelectedFields" style="height: 250px;"><option value="1">Model</option> <option value="2">Manufacturer</option> <option value="3">Type</option> <option value="4">Location</option> <option value="5">Vendor</option> <option value="6">Status</option> <option value="7">ip_address</option> <option value="8">mac_address</option> <option value="9">note</option> <option value="10">owner</option> <option value="11">cost</option> <option value="12">po_number</option> <option value="13">description</option> <option value="14">invoice_number</option> <option value="15">serial_number</option> <option value="16">asset_tag_number</option> <option value="17">acquired_date</option> <option value="18">disposed_date</option> <option value="19">verified_date</option> <option value="20">created_date</option> <option value="21">created_by</option> <option value="22">modified_date</option> <option value="23">modified_by</option> </select> <br /> <input type="submit" value="ExportUsingEPPlus" /> </form> 

现在我试图做的是使用EPPlus库将我的MultiSelectList的选定字段的所有值在我的INV_Assets表中导出为Excel。

ExportController – ExportUsingEPPlus()

  [HttpPost] public ActionResult ExportUsingEPPlus(ExportAssetsViewModel model) { ExcelPackage package = new ExcelPackage(); var ws = package.Workbook.Worksheets.Add("TestExport"); var exportFields = new List<string>(); foreach(var selectedField in model.SelectedFields) { // Adds selected fields to [exportFields] List<string> exportFields.Add(model.ListOfExportFields.First(s => s.Key == selectedField).Value); } // Loops to insert column headings into Row 1 of Excel for (int i = 0; i < exportFields.Count(); i++ ) { ws.Cells[1, i + 1].Value = exportFields[i].ToString(); } // INVALID - Need to query table INV_Assets for all values of selected fields and insert into appropriate columns. if (exportFields.Count() > 0) { ws.Cells["A2"].LoadFromCollection(exportFields); } var memoryStream = new MemoryStream(); package.SaveAs(memoryStream); string fileName = "Exported-InventoryAssets-" + DateTime.Now + ".xlsx"; string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; memoryStream.Position = 0; return File(memoryStream, contentType, fileName); 

对于我当前的代码,如果我在我的MultiSelectListselect[ip_address][mac_address][note][owner][cost] ,我会在我的Excel表格中逐字输出:

 [ip_address] [mac_address] [note] [owner] [cost] 

如何查询我的INV_Assets表,将所选字段的所有数据值插入到相应的列中?


编辑

这是我试图用LINQ查询的INV_Assets模型。 THIS的build议看起来很有希望,但我不太清楚如何使用自己的字段进行设置?

 using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using GridMvc.DataAnnotations; using System.Web.Mvc; using InventoryTracker.Models; namespace InventoryTracker.Models { [GridTable(PagingEnabled = true, PageSize = 30)] public class INV_Assets { // Setting GridColumn Annotations allows you to use AutoGenerateColumns on view to auto create the Grid based on the model. public int Id { get; set; } public int Model_Id { get; set; } [ForeignKey("Model_Id")] public virtual INV_Models Model { get; set; } [Required] public int Manufacturer_Id { get; set; } [ForeignKey("Manufacturer_Id")] public virtual INV_Manufacturers Manufacturer { get; set; } [Required] public int Type_Id { get; set; } [ForeignKey("Type_Id")] public virtual INV_Types Type { get; set; } [Required] public int Location_Id { get; set; } [ForeignKey("Location_Id")] public virtual INV_Locations Location { get; set; } public int Vendor_Id { get; set; } [ForeignKey("Vendor_Id")] public virtual INV_Vendors Vendor { get; set; } [Required] public int Status_Id { get; set; } [ForeignKey("Status_Id")] public virtual INV_Statuses Status { get; set; } public string ip_address { get; set; } public string mac_address { get; set; } [DataType(DataType.MultilineText)] public string note { get; set; } public string owner { get; set; } //[DataType(DataType.Currency)] //[DisplayFormat(DataFormatString="{0:C}", ApplyFormatInEditMode=true)] [DisplayFormat(DataFormatString = "{0:#,###0.00}", ApplyFormatInEditMode=true)] public decimal cost { get; set; } public string po_number { get; set; } [DataType(DataType.MultilineText)] public string description { get; set; } public int invoice_number{ get; set; } [Required] public string serial_number { get; set; } [Required] public string asset_tag_number { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime? acquired_date { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime? disposed_date { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime? verified_date { get; set; } [Required] [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime created_date { get; set; } [Required] public string created_by { get; set; } [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] public DateTime? modified_date { get; set; } public string modified_by { get; set; } // Flag to specify if item is available? (Not signed out, not auctioned, recycled, etc.) //public bool available { get; set; } } } 

编辑2

我相信我得到了正确的文件,因为我需要根据checkbox列表select特定的列 。 该解决scheme说要获得DynamicLibrary.cs ,但在下载中,我发现是Dynamic.cs ? 在VS2013中,我点击了我的项目并添加了一个名为DynamicLibrary.cs的新类。 然后,我将下载的文件中的内容复制/粘贴到这个新的类文件中。

这使我可以using System.Linq.Dynamic进行引用。

但现在我想我已经在错误的地方添加了示例设置? 这就是我的ExportController目前的DynamicColumns代码底部。 最后一节public IQueryable DynamicSelectionColumns()当前还没有被修改 – IQueryableTrackerDataContext()DynamicColumns()当前都被标记为错误。

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using InventoryTracker.DAL; using OfficeOpenXml; using InventoryTracker.Models; using System.Linq.Dynamic; namespace InventoryTracker.Controllers { public class ExportController : Controller { InventoryTrackerContext _db = new InventoryTrackerContext(); // GET: Export public ActionResult Index() { ExportAssetsViewModel expViewMod = new ExportAssetsViewModel(); return View(expViewMod); } public ActionResult Export() { GridView gv = new GridView(); gv.DataSource = _db.INV_Assets.ToList(); gv.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=InventoryAssets-" + DateTime.Now + ".xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gv.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); return RedirectToAction("StudentDetails"); } [HttpPost] public ActionResult ExportUsingEPPlus(ExportAssetsViewModel model) { //FileInfo newExcelFile = new FileInfo(output); ExcelPackage package = new ExcelPackage(); var ws = package.Workbook.Worksheets.Add("TestExport"); var exportFields = new List<string>(); foreach(var selectedField in model.SelectedFields) { // Adds selected fields to [exportFields] List<string> exportFields.Add(model.ListOfExportFields.First(s => s.Key == selectedField).Value); } // Loops to insert column headings into Row 1 of Excel for (int i = 0; i < exportFields.Count(); i++ ) { ws.Cells[1, i + 1].Value = exportFields[i].ToString(); } // INVALID - Need to query table INV_Assets for all values of selected fields and insert into appropriate columns. if (exportFields.Count() > 0) { var exportAssets = from ia in _db.INV_Assets select new { ia.ip_address, } ws.Cells["A2"].LoadFromCollection(exportFields); } var memoryStream = new MemoryStream(); package.SaveAs(memoryStream); string fileName = "Exported-InventoryAssets-" + DateTime.Now + ".xlsx"; string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; memoryStream.Position = 0; return File(memoryStream, contentType, fileName); } } public class DynamicColumns : INV_Assets { //public int Id { get; set; } //public int Model_Id { get; set; } public virtual INV_Models Model { get; set; } //public int Manufacturer_Id { get; set; } public virtual INV_Manufacturers Manufacturer { get; set; } //public int Type_Id { get; set; } public virtual INV_Types Type { get; set; } //public int Location_Id { get; set; } public virtual INV_Locations Location { get; set; } //public int Vendor_Id { get; set; } public virtual INV_Vendors Vendor { get; set; } //public int Status_Id { get; set; } public virtual INV_Statuses Status { get; set; } public string ip_address { get; set; } public string mac_address { get; set; } public string note { get; set; } public string owner { get; set; } public decimal cost { get; set; } public string po_number { get; set; } public string description { get; set; } public int invoice_number { get; set; } public string serial_number { get; set; } public string asset_tag_number { get; set; } public DateTime? acquired_date { get; set; } public DateTime? disposed_date { get; set; } public DateTime? verified_date { get; set; } public DateTime created_date { get; set; } public string created_by { get; set; } public DateTime? modified_date { get; set; } public string modified_by { get; set; } } public enum EnumTasks { Model = 1, Manufacturer = 2, Type = 3, Location = 4, Vendor = 5, Status = 6, ip_address = 7, mac_address = 8, note = 9, owner = 10, cost = 11, po_number = 12, description = 13, invoice_number = 14, serial_number = 15, asset_tag_number = 16, acquired_date = 17, disposed_date = 18, verified_date = 19, created_date = 20, created_by = 21, modified_date = 22, modified_by = 23 } public IQueryable DynamicSelectionColumns() { using (var db = new TrackerDataContext()) { string fieldIds = "," + "4,5,3,2,6,17,11,12" + ","; var taskColum = Enum.GetValues(typeof(EnumTasks)).Cast<EnumTasks>().Where(e => fieldIds.Contains("," + ((int)e).ToString() + ",")).Select(e => e.ToString().Replace("_", "")); string select = "new ( TaskId, " + (taskColum.Count() > 0 ? string.Join(", ", taskColum) + ", " : "") + "Id )"; return db.Task.ToList().Select(t => new DynamicColumns() { Id = t.Id, TaskId = Project != null ? Project.Alias + "-" + t.Id : t.Id.ToString(), ActualTime = t.ActualTime, AssignedBy = t.AssignedBy.ToString(), AssignedDate = t.AssignedDate, AssignedTo = t.AssignedTo.ToString(), CreatedDate = t.CreatedDate, Details = t.Details, EstimatedTime = t.EstimatedTime, FileName = t.FileName, LogWork = t.LogWork, Module = t.Module != null ? t.Module.Name : "", Priority = t.Priority != null ? t.Priority.Name : "", Project = t.Project != null ? t.Project.Name : "", ResolveDate = t.ResolveDate, Status = t.Status != null ? t.Status.Name : "", Subject = t.Subject, TaskType = t.TaskType != null ? t.TaskType.Type : "", Version = t.Version != null ? t.Version.Name : "" }).ToList().AsQueryable().Select(select); } } } 

在哪里/如何设置这个代码来使用Linq DynamicColumns()