我有以下代码:
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();
}
}
当在动态属性上使用$ select时,结果包含许多不包含属性的空对象。让我们在这个例子中说如果查询是http://localhost:58020/Books?$select=K2
,我得到的响应是:
{
@odata.context: "http://localhost:58020/$metadata#Books(k2)",
value: [
{
k2: "v2"
},
{ }
]
}
如果您发现它包含一本不包含属性k2
的书的空括号。如何摆脱这种行为?。
答案 0 :(得分: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();
}
}