简体   繁体   中英

Call a custom method in linq query

I need to call a custom method in linq query, eg:

IQueryable<Person> query = _db.Persons.OrderBy(p => Decrypt(p.Name));

However, in this case Decrypt gives me an exception.

I also tried with this approach:

IQueryable<Person> query = _db.Persons.AsEnumerable()
                                      .OrderBy(p => Decrypt(p.Name))
                                      .AsQueryable<Person>();

However in this case it works but as I'm using this query as a source (SelectMethod) for my ListView, paging is not working when using DataPager control.

You need to actually figure out why IS the paging not working. It's possible to create custom SQL function and let Decrypt work. For that, you need to create SQL function Decrypt that does the work.

This is simple example:

(SQL part)

CREATE FUNCTION ReverseCustName(@string varchar(100))
RETURNS varchar(100)
AS
BEGIN
    DECLARE @custName varchar(100)
    -- Implementation left as exercise for users.
    RETURN @custName
END

and LINQ part

[Function(Name = "dbo.ReverseCustName", IsComposable = true)]
[return: Parameter(DbType = "VarChar(100)")]
public string ReverseCustName([Parameter(Name = "string",
    DbType = "VarChar(100)")] string @string)
{
    return ((string)(this.ExecuteMethodCall(this,
        ((MethodInfo)(MethodInfo.GetCurrentMethod())),
        @string).ReturnValue));
}

See this for more information: http://msdn.microsoft.com/en-us/library/bb386973(v=vs.110).aspx

if its LINQ to SQL you cant since it tries to render that to real SQL. try to cast the Persons to another object class of your own and then it will be Linq to Object and there it will work. i had this issue a few times, i played with it a little bit until it worked.

BTW i think one of the linq extensions is looking for an IComparable, so worse case you can just implement one

I will give you a one-liner which "could" work, but please provide the exception as well.

var query = _db.Persons.AsEnumerable().OrderBy(p => Decrypt(p.Name));

Your problem is probably, but it is hard to know since we are not given the exception, that you are trying to get your database to execute Decrypt which is not possible. The added ToList() just enumerates, ie fetches the data from database in this case, and then we can order in memory.

You won't get paging to work the way you want since the database cannot execute the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM