2015-07-09 82 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