简体   繁体   English

在EntityFramework结果上应用自定义方法

[英]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. 当然,由于EF6无法将我的方法转换为SQL查询,因此会引发异常。 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, 如果您对linq方法链样式没有任何疑问,可以执行以下操作,

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. .AsEnumerable()调用从本质上告诉EF,该调用之后发生的事情不应转换为数据库逻辑。 It doesn't execute any code. 它不执行任何代码。 It just changes the type of the expression from an IQueriable<T> into an IEnumerable<T> . 它只是将表达式的类型从IQueriable<T>更改为IEnumerable<T>

See the AsEnumerable documentation for more information. 有关更多信息,请参见AsEnumerable文档

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". 除非您可以使用EF提供的SqlFunctions之一,否则您必须构建自己的表达式树,而且我认为,如果MyCustomMethod的作用是“将byte []反序列化为对象并对其反序列化”,那将是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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