我想查询WCF数据服务并使用结果信息将其数据绑定到DataGridView。我见过的所有样本(like this official one)都假设了最简单的场景,它始终选择单个实体的所有列。但是,在大多数情况下,我需要来自相关实体的信息,我不希望查询实体的每个字段:
Int32 iIDFilter = 3;
TestEntities oTestDB = new 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);
在上面的代码中,我会收到错误,因为我无法创建DataServiceCollection,因为我选择了TBLTable1的某些字段,以及某些相关实体的某些字段。有没有办法解决?当我使用WCF数据服务时,是否总是必须选择实体的所有字段,没有相关字段?我可以至少对结果做foreach
吗?
TKS
答案 0 :(得分:0)
限制是查询必须返回“实体”。到达那里的最简单方法是返回表示您尝试获取的实体的类的实例。然后,您可以将其子集化为仅包含所需的属性。您也不能“展平”结果,因此如果您只想要相关实体上的一部分属性,则需要投影该实体,但只需要对其进行一些属性。例如(我添加了对演示OData.org服务的引用):
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);
}
这将运行此网址:
http://services.odata.org/OData/OData.svc/Products()?$expand=Category&$select=ID,Name,Category/ID,Category/Name