简体   繁体   中英

Apply a custom method on EntityFramework results

Is there a way to do something like this?

using (var db = new MyEntities())
{
    // getting all users with EntityFramework 6
    var allUsers = from u in db.Users
                   select new
                   {
                       MyCustomMethod(u.FirstName)
                   };
}

Of course, because EF6 cannot translate my method to an SQL query it throws an exception. Then what I need to do was to create another loop on that result and run my method on the member, is there a way to not be needing that second loop?

If you do not have any problem with linq method chain style you can do something like this,

db.Users.AsEnumerable().Select(method);

And write some method like this,

 public string method(User a)
 {
     return a.UserName;
 }

You can do this:

var databaseUsers = from u in db.Users
                    /* add clauses to execute in the database here */
                    select new { u.FirstName };

var allUsers = from u in databaseUsers.AsEnumerable()
               select new
               {
                   MyCustomMethod(u.FirstName)
               };

The .AsEnumerable() call essentially tells EF that what happens after the call should not be translated into database logic. It doesn't execute any code. It just changes the type of the expression from an IQueriable<T> into an IEnumerable<T> .

See the AsEnumerable documentation for more information.

Well I'm afraid you can't.

Unless you can use one of the SqlFunctions EF provides, you have to build your own expression tree, and I guess it won't be possible if the role of MyCustomMethod is to "deserializes an byte[] to and object".

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