如何从对象上下文返回特定的DataRow对象?

时间:2012-06-28 14:33:10

标签: c# entity-framework lambda wcf-ria-services

我正在使用Entity Framework和Silverlight(RIA),我正在考虑创建一个扩展CRUD的函数,以允许用户指定特定的列名,然后使用匹配的值来精确定位记录。 ..代码看起来像这样......

public IQueryable<Category> GetCategory(string theColumn, string theCriteria)
{
      return this.ObjectContext.Categories
                .Where(c => c.theColumn = theCriteria);
}

获取所有类别的类似工作函数...(在关联数据模型后通过构建创建)

    public IQueryable<Category> GetCategories()
    {
        return this.ObjectContext.Categories;
    }

提前致谢!

3 个答案:

答案 0 :(得分:1)

我不知道这是解决你的问题还是仅移动它但你可以将谓词委托给方法的客户端,如下所示

public IQueryable<Category> GetCategory(Func<Category, IQueryable<Category>> predicate)
{
      return this.ObjectContext.Categories.Where(predicate);
}

然后你可以通过这种方式调用这个方法

GetCategory(c => c.column=criteria)

答案 1 :(得分:1)

我已经构建了类似于你想要构建的东西。我使用System.Linq.Expressions中的表达式树构建。因此,我建议您使用表达式树构建where where谓词,其中谓词的签名为Expression<Func<T,bool>>

下面的一些伪代码,其中T是WCF RIA实体:

public static class QueryHelper
{
  public static Expression<Func<T, bool>> ToPredicate<T> ( string propertyName, dynamic criteria )
    {
        ParameterExpression pe = Expression.Parameter( typeof( T ), "t" );
        Expression np = Expression.Property( pe, propertyName );
        ConstantExpression value = Expression.Constant( criteria );

        Expression e1 = Expression.Equal( np, value );

        var filter = Expression.Lambda<Func<T, bool>>( e1, pe );

        return filter;
    }
}

然后可以使用:

var selector = QueryHelper.ToPredicate<Category>("theColumn", "hello");
return this.ObjectContext.Categories.Where(selector);     

LoadOperation<Employee> loader = context.Load( context.GetEmployeesQuery()
                                        .Where( selector ) );
loader.Completed += (op) =>
  {
    if ( !op.HasErrors)
    {
    }
  };

或者

var selector = QueryHelper.ToPredicate<Category>("theColumn", true);
return this.ObjectContext.Categories.Where(selector); 

需要注意的一点是表达式e1 = Expression。 Equal (np,value);在功能中。您可以扩展此功能以执行&gt;,&lt;,=&gt;等,但您需要检查您使用的属性类型是否支持运算符。

希望这有帮助。

答案 2 :(得分:0)

我像这样初始化我的上下文...

    NorthwindDomainContext context = new NorthwindDomainContext();

我这样称呼你的方法......

var selector = QueryHelper.ToPredicate<Employee>("theColumn", "hello");
        return this.context.Employees.Where(selector);  

另外,正如我所说,我实际上使用的是Employee而不是Category。想法?

错误1参数2:无法从'System.Linq.Expressions.Expression&gt;'转换到'System.Func'C:\ Code \ NorthwindRIA \ NorthwindRIA \ Views \ Employee.xaml.cs 22 49 NorthwindRIA

错误2'System.ServiceModel.DomainServices.Client.EntitySet'不包含'Where'的定义和最佳扩展方法重载'System.Linq.Queryable.Where(System.Linq.IQueryable,System.Linq。 Expressions.Expression&gt;)'有一些无效的参数C:\ Code \ NorthwindRIA \ NorthwindRIA \ Views \ Employee.xaml.cs 22 20 NorthwindRIA

错误3实例参数:无法从'System.ServiceModel.DomainServices.Client.EntitySet'转换为'System.Linq.IQueryable'C:\ Code \ NorthwindRIA \ NorthwindRIA \ Views \ Employee.xaml.cs 22 20 NorthwindRIA < / p>