$select动态属性
本文关键字:属性 动态 select | 更新日期: 2023-09-27 18:02:02
我有以下代码:
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
属性的书。如何摆脱这种行为?
这是《字典》的一期。您可以做的是创建一个名为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();
}
}