Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework LINQ Query using Custom C# Class Method - Once yes, once no - because executing on the client or in SQL?
    primarykey
    data
    text
    <p>I have two Entity Framework 4 Linq queries I wrote that make use of a custom class method, one works and one does not:</p> <p>The custom method is:</p> <pre><code>public static DateTime GetLastReadToDate(string fbaUsername, Discussion discussion) { return (discussion.DiscussionUserReads.Where(dur =&gt; dur.User.aspnet_User.UserName == fbaUsername).FirstOrDefault() ?? new DiscussionUserRead { ReadToDate = DateTime.Now.AddYears(-99) }).ReadToDate; } </code></pre> <p>The linq query that works calls a from after a from, the equivalent of SelectMany():</p> <pre><code> from g in oc.Users.Where(u =&gt; u.aspnet_User.UserName == fbaUsername).First().Groups from d in g.Discussions select new { UnReadPostCount = d.Posts.Where(p =&gt; p.CreatedDate &gt; DiscussionRepository.GetLastReadToDate(fbaUsername, p.Discussion)).Count() }; </code></pre> <p>The query that does not work is more like a regular select:</p> <pre><code> from d in oc.Discussions where d.Group.Name == "Student" select new { UnReadPostCount = d.Posts.Where(p =&gt; p.CreatedDate &gt; DiscussionRepository.GetLastReadToDate(fbaUsername, p.Discussion)).Count(), }; </code></pre> <p>The error I get is:</p> <pre><code>LINQ to Entities does not recognize the method 'System.DateTime GetLastReadToDate(System.String, Discussion)' method, and this method cannot be translated into a store expression. </code></pre> <p>My question is, why am I able to use my custom GetLastReadToDate() method in the first query and not the second? I suppose this has something to do with what gets executed on the db server and what gets executed on the client? These queries seem to use the GetLastReadToDate() method so similarly though, I'm wondering why would work for the first and not the second, and most importantly if there's a way to factor common query syntax like what's in the GetLastReadToDate() method into a separate location to be reused in several different other LINQ queries. </p> <p>Please note all these queries are sharing the same object context.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload