Say I have an Employee entity, and each Employee has many EmployeeChange entities.
An Employee and EmployeeChange looks like:
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; }
}
Is there a LINQ query that can flatten these to make something like the below for us in a MVC ViewModel, without listing every single property? I.e. If I add/remove properties in my Entity or Entity class, I want the LINQ query to not have to change. The below of course is dynamically generated from a projection in the LINQ query rather than being an actually declared class. One important thing is any DataAnnotations will need to be preserved so they are accessible to the view:
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; }
}
I've tagged this with reflection because I understand that it may not be possible without using reflection.