我正在嘗試構建一個數據集,以便將其導出到電子表格中,並且必須承認我已達到飽和點! 這些都是我的表:如何使用linq構建動態查詢
**Matrix**
Employee id
Template id
Expiry date
**Employee**
Id
Employee Name
**Template**
Template Id
Template Name
我所試圖實現的是所有員工(其中員工將組成數據集的行)的列表和所有模板列表(模板列頭)然後我需要爲每個員工填寫每個模板的截止日期。由於他們還沒有獲得認證,有些員工將不會有每個模板的失效日期。
我想創造一個員工列表,然後將員工集合矩陣的對象,但不一定會工作,不會每個人都會有每個模板類型的矩陣中的條目中。
我已經使用LINQ工作了好幾年,但我在這裏有點爲難,因爲這組數據是如何動態的構建。定期添加新模板,因此無需維護查詢。它甚至可以通過使用linq,或者我需要看看在SQL中建立一個視圖?
任何幫助將不勝感激。以下是我正在嘗試做的一個簡單例子!
Temp1 temp2 temp3 temp4
Emp1 01/01/2014 02/6/2015 04/06/2012
Emp2 02/6/2015
Emp3 01/05/2010
這是我的數據結構:
編輯
嗯,我還是設法得到的東西的工作,我可以輸出到的格式圖我描述過,但我不知道它是否特別高效 - 如果有更好的方法,我很想知道它是如何的!
public class EmpMatrix
{
public int TemplateId { get; set; }
public string TemplateName { get; set; }
public DateTime? ExpiryDate { get; set; }
}
public class Classemptemp
{
public emp Employee { get; set; }
public List<EmpMatrix> tempateList { get; set; }
}
public DateTime? GetExpiry(int template, int empl)
{
return (from a in _entities.matrices
where a.empid == empl && a.tempId == template
select a.expiryDate).FirstOrDefault();
}
public List<Classemptemp> testing()
{
List<emp> employees = _entities.emps.ToList();
List<template> TemplateList = _entities.templates.ToList();
List<Classemptemp> empList = (from employee in employees
let matrix = TemplateList.Select(template => new EmpMatrix
{
TemplateId = template.templateId, TemplateName = template.Name, ExpiryDate = GetExpiry(template.templateId, employee.Id)
}).ToList()
select new Classemptemp
{
Employee = employee, tempateList = matrix
}).ToList();
return empList;
}
首先,是的,它似乎是可能的。然而,你已經有了一些含糊的代碼。你有DbContext嗎?你對視圖有約束力嗎?有兩個階段來回答這個問題,一個是:我需要什麼查詢和兩個:我如何將數據表示爲上面的表格。 – Heberda
我正在使用MVC,我打算將查詢結果綁定到數據網格,然後從控制器操作返回文件結果,以直接將數據作爲csv傳回客戶端。我有一個包含每個表的EDMX,並使用_entites訪問實體。所以我可以通過說_entities.employee.ToList();來獲得員工名單。 –
我明白了。你有導航屬性嗎?你的POCO課程是什麼樣的? – Heberda