2012-01-04 38 views
1

我有以下問題。我有在具有性能,如實體框架模型類:將單個實體框架對象轉換爲字典

class Company{ 
    public string Name {get; set}; 
    public string Address {get; set}; 
    public string Email{get; set}; 
    public string WebSite {get; set}; 
} 

我有配置在定義某些字段是否應該被顯示或不數據庫如:

  • 名稱:顯示
  • 地址:顯示
  • 電子郵件:隱藏
  • 網站:隱藏

這是動態的,所有字段都按名稱引用。

當我在視圖中顯示對象。將單個對象轉換爲某個字典是很好的選擇,其中鍵的屬性名稱和值將是屬性值,因此我可以通過名稱檢查每個字段是否應該顯示它(可能在某些for-each循環中)例如:

CompanyDetails.cshtml

<h2>Company Details</h2> 
@foreach(var property in modelDictionary.Keys){ 

    @if(IsVisible(property)) 
     @Html.Raw(modelDictionary[property]) 
} 

什麼是單個對象從實體框架模型轉換爲性能的字典的最佳方式?我應該將它從控制器操作中的對象轉換爲字典還是以某種方式在視圖中使用模型元數據?

我可以在公司類中使用反射並查找類中的所有屬性,以便我可以填充字典,但是這看起來像是過於老派的解決方案,所以我徘徊有沒有更好的方法來做到這一點?

感謝

+0

我米有點困惑你正在努力完成和爲什麼。你爲什麼不在視圖中顯示某個字段?或者,向模型字段添加一個屬性,以確定它們是否可以顯示(但我認爲我的第一個建議更容易/更有意義)? – JasCav 2012-01-04 18:02:06

+0

我想避免重複添加以下條件:@if(IsVisible(「Name」))

@Html.Raw(model.Name)
@if(IsVisible(「Address」))
@Html.Raw(model.Address)
等等。想象一下,您有很多應該被相同的字段包圍如果條件。在模型中,我使用類似c = companies.Where(company => company.ID == parID)的方式返回所有字段;我有一個與DataSet類似的早期代碼,我在單個foreach循環中引用了具有列名稱的單元格。雖然它是一個DataSet,但它是優雅的解決方案,所以我想在這裏做類似的事情。 – 2012-01-04 19:37:00

回答

2

你可以使用一個RouteValueDictionary它允許你將對象轉換成字典:

public class Company 
{ 
    public string Name { get; set; } 
    public string Address { get; set; } 
    public string Email { get; set; } 
    public string WebSite { get; set; } 
} 

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new Company 
     { 
      Address = "some address", 
      Email = "some email", 
      Name = "some name", 
      WebSite = "some website" 
     }; 
     return View(new RouteValueDictionary(model)); 
    } 
} 

,並在視圖:

@model RouteValueDictionary 

<h2>Company Details</h2> 
@foreach (var item in Model) 
{ 
    if (IsVisible(item.Key)) 
    { 
     <div>@item.Value</div> 
    } 
} 
1

你可以實現你的實體的索引和映射使得槽式反射在實體的屬性之一。

喜歡的東西:

class Entity 
{ 
    public bool this[int index] 
    { 
     get 
     { 
      // Select all properties, order by name and return the property index 
     } 
    } 

    public bool this[string name] 
    { 
     get 
     { 
      // Select all properties and return the correct one. 
     } 
    } 
}