I want to query a WCF Data Service and use the resulting information to databind it to a DataGridView. All the samples I've seen (like this official one) assume the most simple scenario, which is always selecting all columns of a single entity. However, on most cases, I want information from related entities and I don't want every field for the entity being queried:
Int32 iIDFilter = 3;
TestEntities oTestDB = n开发者_运维知识库ew TestEntities(new Uri("http://desk01:9877/TestEntities/"));
var oConsulta1 = from a in oTestDB.TBLTable1s
where a.IDField1 == iIDFilter
select new
{
IDField1 = a.IDField1,
IDField2 = a.TBLTable2.IDField1,
IDField3 = a.IDField3,
IDField4 = a.TBLTable3.IDField1,
IDField5 = a.IDRSGroup,
IDField6 = a.TBLTable4.IDField1
};
DataServiceCollection<TBLTable1> eventos = new DataServiceCollection<TBLTable1>(oConsulta1);
On the code above, I'll get an error, since I can't create the DataServiceCollection, because I've selected some fields of TBLTable1, and also some fields of some related entities. Is there any way around this? Do I always have to select all the fields of an entity, with no related fields, when I use WCF Data Services? Can I at least do a foreach
on the result?
The limitation is that the query has to return "entities". The easiest way to get there is to return instances of the classes which represent the entities you're trying to get. Then you can subset it to only include the properties you want. You also can't "flatten" the results, so if you want just a subset of the properties on a related entity, you need to project that entity, but only some properties on it. For example (I added a reference to the demo OData.org service):
DemoService ctx = new DemoService(new Uri("http://services.odata.org/OData/OData.svc/"));
var query = from p in ctx.Products
select new Product()
{
ID = p.ID,
Name = p.Name,
Category = new Category()
{
ID = p.Category.ID,
Name = p.Category.Name
}
};
DataServiceCollection<Product> products = new DataServiceCollection<Product>(query);
foreach (var p in products)
{
Console.WriteLine(p.Category.Name);
}
This will run this URL:
http://services.odata.org/OData/OData.svc/Products()?$expand=Category&$select=ID,Name,Category/ID,Category/Name
精彩评论