【发布时间】:2011-10-31 17:28:45
【问题描述】:
假设我有一个 Employee 实体,每个 Employee 都有许多 EmployeeChange 实体。
一个 Employee 和 EmployeeChange 看起来像:
class Employee
{
[Key]
public int EmployeeKey {get;set;}
public string EmployeeName { get; set; }
public int CurrentEmployeeChangeKey { get; set; }
[ForeignKey("CurrentEmployeeChangeKey")]
public virtual EmployeeChange CurrentEmployeeChange {
get { return EmployeeChanges.FirstOrDefault() ; } /*set;*/ }
public virtual ICollection<EmployeeChange> EmployeeChanges { get; set; }
}
class EmployeeChange
{
[Key]
public int EmployeeChangeKey { get; set; }
public int EmployeeKey { get; set; }
[ForeignKey("EmployeeKey")]
public virtual Employee Employee { get; set; }
public string EmployeeStreet { get; set; }
public string EmployeeCity { get; set; }
public string Etc { get; set; }
public DateTime ChangeEffective { get; set; }
}
是否有一个 LINQ 查询可以将它们展平,以便在 MVC ViewModel 中为我们制作类似下面的内容,而不列出每个属性?即如果我在 Entity 或 Entity 类中添加/删除属性,我希望 LINQ 查询不必更改。下面当然是从 LINQ 查询中的投影动态生成的,而不是实际声明的类。一件重要的事情是需要保留任何 DataAnnotations,以便视图可以访问它们:
class EmployeeCurrentChange
{
public string EmployeeName { get; set; }
public string EmployeeStreet { get; set; }
public string EmployeeCity { get; set; }
public string Etc { get; set; }
public DateTime ChangeEffective { get; set; }
//I don't need the below properties in the result, but if they
//happen to be there I don't mind.
public int EmployeeKey { get; set; }
[ForeignKey("EmployeeKey")]
public virtual Employee Employee { get; set; }
[Key]
public int EmployeeKey {get;set;}
public int CurrentEmployeeChangeKey { get; set; }
[ForeignKey("CurrentEmployeeChangeKey")]
public virtual EmployeeChange CurrentEmployeeChange {
get { return EmployeeChanges.FirstOrDefault() ; } /*set;*/ }
public virtual ICollection<EmployeeChange> EmployeeChanges { get; set; }
[Key]
public int EmployeeChangeKey { get; set; }
}
我已将其标记为反射,因为我知道不使用反射可能无法实现。
【问题讨论】:
标签: c# asp.net-mvc linq reflection