【问题标题】:Querying related tables in WCF Data Services and databinding在 WCF 数据服务和数据绑定中查询相关表
【发布时间】:2011-01-22 18:14:39
【问题描述】:

我想查询 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 吗?
提示

【问题讨论】:

    标签: linq-to-entities wcf-data-services


    【解决方案1】:

    限制是查询必须返回“实体”。到达那里的最简单方法是返回代表您尝试获取的实体的类的实例。然后您可以将其子集以仅包含您想要的属性。您也不能“展平”结果,因此如果您只想要相关实体上的属性子集,则需要投影该实体,但只需要其上的一些属性。例如(我添加了对演示 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);
    }
    

    这将运行此 URL:

    http://services.odata.org/OData/OData.svc/Products()?$expand=Category&$select=ID,Name,Category/ID,Category/Name
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      相关资源
      最近更新 更多