2013-11-04 79 views
0

選擇的參數我有一個實體:返回從LINQ對象

public class Branch 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int BranchID { get; set; } 
    public string Name { get; set; } 
    public string Address1 { get; set; } 
    public string Address2 { get; set; } 
    public string Postcode { get; set; } 
    public string City { get; set; } 
    public string State { get; set; } 
    public string Country { get; set; } 
} 

我有一個apicontroller函數返回的樹枝對象:

IEnumerable<Branch> branches = null; 
branches = repository.Branches.Where(b => b.LastModified > modifiedSince).AsEnumerable(); 

return branches; 

我怎麼只能返回BranchIDName

我已經試過這樣:

IEnumerable<Branch> branches = null; 

branches = repository.Branches 
    .Where(b => b.LastModified > modifiedSince) 
    .Select(b => new Branch {BranchID = b.BranchID, Name = b.Name }) 
    .AsEnumerable(); 

return branches; 
+0

您試過了,發生了什麼問題? – nawfal

回答

3

有很多方法可以做到這一點。這一切取決於你如何處理返回的IEnumerable<Branch>

1)你可以做一個匿名類型,但返回它將需要更多的黑客。

var branches = repository.Branches 
          .Where(b => b.LastModified > modifiedSince) 
          .Select(b => new { b.BranchID, b.Name }) 
          .AsEnumerable(); 

2),或者你可以返回的idname的元組。

var branches = repository.Branches 
          .Where(b => b.LastModified > modifiedSince) 
          .Select(b => Tuple.Create(b.BranchID, b.Name)) 
          .AsEnumerable(); 
return branches; 

3)您可能希望創建自己的類,它擁有一個分支的只是ID和名稱。

4)或者你也可以提供一個分支類的替代構造函數,只有作爲參數傳遞的nameid。所有這一切都取決於你的背景。

我傾向於喜歡這裏的元組方法。