Page 1 of 1

function call in linq query

Posted: Sat 12 Feb 2011 10:00
by seser
lets say we have a function "some_function(int) : int"
and i want to build an linq sql query "select * from some_table where some_function(some_field) > some_value)"

i haven't try but

var db = new DbContext();
var results = db.SomeTable.Where(a => db.SomeFunction(a.SomeField) > some_value);

seems meaningfull.

kowever, i also need to assign this where clause a variable in type >, so i can give it to another form as parameter.

in this case "a => db.SomeFunction(a.SomeField) > some_value)" part will not work in another form, so that "db" object might have been disposed,

Posted: Mon 14 Feb 2011 16:07
by StanislavK
The problem is that a command executed on a DataContext instance should not refer to objects from another DataContext. Thus, even if the first DataContext object is not disposed yet, trying to pass such predicate will cause InvalidOperationException.

We can only suggest writing a function that receives DataContext and returns IQueryable (i.e., the return of the Where method) as a workaround.

Also, could you please describe the scenario in which you need to pass a predicate of such form?

Posted: Mon 14 Feb 2011 21:54
by seser
thanks for concern

I have a form, userListForm, which has a variable List>> named "filters". as can be understood from its name, i apply these functions before i bind data.

I have another form, which creates this Expressions and adds expressions in userListform.

now this from uses datacontext which is created in userListform.
in this case program works.

i was asked for, if there is any feature so we can use function name as string.

Posted: Wed 16 Feb 2011 14:53
by StanislavK
For example, you can change the DataContext object referred to in the expression when adding it (the expression) to the list. To do so, you can create a descendant of the System.Linq.Expression.ExpressionVisitor class:
http://msdn.microsoft.com/en-us/library ... sitor.aspx
With this descendant, you can 'attach' the expression to another DataContext (i.e., the one residing on the second form).

I will send you a test project, please check that it was not blocked by your mail filter. Notice that the ExpressionVisitor class is available in .NET Framework 4.0 only. In case you are using .NET Framework 3.5, you will also need to implement a System.Linq.Expressions.ExpressionVisitor analog (please see the definition of such class in the sample).

The database objects used in the sample are defined as follows:

Code: Select all

CREATE TABLE dept
(
  deptno integer NOT NULL,
  dname character varying(14),
  loc character varying(13),
  CONSTRAINT dept_pkey PRIMARY KEY (deptno)
);

CREATE OR REPLACE FUNCTION plus_one("input" integer)
  RETURNS integer AS
$BODY$
BEGIN
  RETURN input + 1;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;