2015-07-09 115 views
0

我有以下代碼:

public class Book 
{ 
    [Key] 
    public string ISBN { get; set; } 
    public string Title { get; set; } 
    public Press Press { get; set; } 
    public IDictionary<string, object> Properties { get; set; } 
} 

public class BooksController : ODataController 
{ 
    private IList<Book> _books = new List<Book> 
    { 
     new Book 
     { 
      ISBN = "978-0-7356-7942-9", 
      Title = "Microsoft Azure SQL Database Step by Step", 

      Properties = new Dictionary<string, object> 
      { 
       {"k1","v1"}, 
       {"k2","v2"} 
      } 
     }, 
     new Book 
     { 
      ISBN = "978-0-7356-8383-9", 
      Title = "SignalR", 
      Press = new Press 
      { 
       Name = "Microsoft Press", 
       Category = Category.Book 
      }, 
      Properties = new Dictionary<string, object> 
      { 
       {"k1","v1"} 
      } 
     } 
    }; 

    [EnableQuery] 
    public IQueryable<Book> Get() 
    { 
     return _books.AsQueryable(); 
    } 
} 

當$選擇是在動力性使用,結果包含了很多對於那些不包含財產空對象。讓我們在這個例子說,如果查詢是http://localhost:58020/Books?$select=K2,我得到的迴應是:

{ 
    @odata.context: "http://localhost:58020/$metadata#Books(k2)", 
    value: [ 
    { 
     k2: "v2" 
    }, 
    { } 
    ] 
} 

如果你觀察它包含了一本書,不包含財產k2空括號。如何擺脫這種行爲?

回答

0

這是一個字典問題。你可以做的是創建一個名爲Parameter和,而不是使用Dictionary<String, object>新的類,使用List<Parameter>類似如下:

class Parameter { 
    public String Key; 
    public Object Value; 
} 

修改代碼:

public class Book 
{ 
    [Key] 
    public string ISBN { get; set; } 
    public string Title { get; set; } 
    public Press Press { get; set; } 
    public List<Parameter> Properties { get; set; } 
} 
public class BooksController : ODataController 
{ 
    private IList<Book> _books = new List<Book> 
    { 
     new Book 
     { 
      ISBN = "978-0-7356-7942-9", 
      Title = "Microsoft Azure SQL Database Step by Step", 

      Properties = new List<Parameter> 
      { 
       new Parameter { Key = "k1", Value = "v1" }, 
       new Parameter { Key = "k2", Value = "v2" } 
      } 
     }, 
     new Book 
     { 
      ISBN = "978-0-7356-8383-9", 
      Title = "SignalR", 
      Press = new Press 
      { 
       Name = "Microsoft Press", 
       Category = Category.Book 
      }, 
      Properties = new List<Parameter> 
      { 
       new Parameter { Key = "k1", Value = "v1" } 
      } 
     } 
    }; 

    [EnableQuery] 
    public IQueryable<Book> Get() 
    { 
     return _books.AsQueryable(); 
    } 
} 
+0

克瓦,感謝您的嘗試,但這不會工作。有字典的原因是支持開放式。字典中的鍵和相應的值將像get調用中的Book的聲明屬性一樣呈現。將它轉換爲列表不是一種合適的方法。你可能想看看這個[鏈接](http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/use-open-types -in-的OData-V4) – Prashanth