【问题标题】:Flatten/expand columns of Navigation Property for ViewModel?展平/扩展 ViewModel 的导航属性列?
【发布时间】: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


    【解决方案1】:

    看看这个问题:How to create LINQ Expression Tree to select an anonymous type

    基本上,他创建了一个可以在运行时投影匿名类型的类,您可能可以对其进行调整以供您使用。但是由于它是一个匿名类型并且它是在运行时生成的,所以你不会得到任何类型的设计时支持。由于类型是在运行时生成的,尽管您可以将属性附加到投影以复制当前类中存在的内容。

    老实说,我不知道你为什么要这样做,因为它的工作量很大,但我想我会传递我对这个主题的了解。

    【讨论】:

      猜你喜欢
      • 2012-12-06
      • 2015-02-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 2016-11-13
      • 1970-01-01
      • 2018-08-30
      • 2017-07-17
      相关资源
      最近更新 更多