2016-07-22 17 views
0

只要我只選擇一個列,我沒有問題通過帶有或不帶.Select()方法的視圖模式將Linq查詢結果傳遞給視圖。當我嘗試使用。選擇()選項,像這樣一個重命名的列:添加帶列重命名結果的Linq方法到viewModel

var custodians = _custodian.Contacts 
    .Where(c => !(c.personid.StartsWith("RMR") || c.personid.StartsWith("GMS"))) 
    .Select(c => new { c.contactid, name = c.lname + ", " + c.fname}) 
    .ToList(); 

它創建創建一個System.Collections.Generic.List<<>f__AnonymousType1<int, string>>類型列表

我有一個現有的視圖模型,我傳遞給我的看法:

public class AssetViewModel 
{ 
    public string PsgcTagNumber { get; set; } 
    public string[] AssetAttributes { get; set; } 
    public string Message { get; set; } 
    public Asset Asset { get; set; } 
    public Location Location { get; set; } 
    public string Custodian { get; set; } 
    public ?????? AllContacts { get; set; } 
} 

我不能弄清楚的是用於viewModel的AllContacts屬性的數據類型。

任何人都指向正確的方向?

回答

0

您需要定義一個類。

public class Contact { 
    public int contactid {get;set;} 
    public string name {get;set;} 
} 

.Select(c => new Contact { contactid = c.contactid, name = c.lname + ", " + c.fname}) 

public Contact[] AllContacts { get; set; } 

或只保留實體孤單的,沒有您的查詢做Select方法,並在您的視圖模型使用它 - 你可以添加一個FormattedName財產或類似的東西來處理你的名字。

+0

這是我錯過的部分。我已經定義了該類,只是沒有將選擇投射到該類。我正在試圖在選擇後投射它。謝謝 –

0

您的匿名類型的結果正是你的選擇是生產new { c.contactid, name = c.lname + ", " + c.fname} - INT <列表 - >字符串或{ int contactid, string name } 如果要使用現有的模型,如您AssetViewModel.AllContacts你需要首先確定其類型的列表作爲@Joe伊諾斯陳述,然後更新您的查詢一點點:

var vm = new AssetViewModel 
{ 
    PsgcTagNumber =..., 
    ..., 
    Custodian =..., 
    AllContacts = _custodian.Contacts 
       .Where(c => !(c.personid.StartsWith("RMR") || c.personid.StartsWith("GMS"))) 
       .Select(c => new Contact { c.contactid, name = c.lname + ", " + c.fname}) 
       .ToList(); 
} 

,那麼你就會明白:你的視圖模型,發起並準備向前傳遞