3

这是一个 SL/WPF 应用程序,试图显示两列。以下代码:

MyDomainContext context = new MyDomainContext();
dataGrid1.ItemsSource = context.DBTables;
context.Load(context.GetTwoDataBasesQuery())

;

domainservice.cs 包含方法定义如下:

public IQueryable<DBTable>GetTwoDataBases()
  {
    return this.ObjectContext.DBTables;
  }

此代码工作正常,但返回上下文中的所有列我只需要返回两列,因此更改如下

public IQueryable<DBTable>GetTwoDataBases()
  {
      //trying to return columns
      return GetDBTables().Select(m => new { m.col1, m.col2 });                           
  }

但是编译器产生错误,不接受“return”。

以下错误无法将类型“System.Linq.IQueryable”隐式转换为“System.Linq.IQueryable”。存在显式转换。

如何只返回两列?多于X

4

1 回答 1

1

您正在返回匿名类型,但您拥有的集合的返回类型是DBTable. 您可以创建返回类型object或定义一个新的class并创建该类的对象。

将对象作为返回类型

public object GetTwoDataBases()
{
     //trying to retrun columns
     return GetDBTables().Select(m => new { m.col1, m.col2 });    
}

或者,返回 IQueryable 而不是匿名类型

public IQueryable<YourCustomType>GetTwoDataBases()
{
     //trying to retrun columns
     return GetDBTables()
            .Select(m => new YourCustomType { YourCustomTypeProperty1 = m.col1, YourCustomTypeProperty2 = m.col2 });    
}
于 2013-10-02T04:05:58.243 回答