2

If I have this SQL query:

"select distinct top 1 'PostId' = isnull(RootPost,Id), PostedDateTimeUtc from Post order by PostedDateTimeUtc desc"

And I need to enumerate the results with a DataContext. That is to say, how do I send this SQL to a DataContext and parse the result?

How do I do that? What would a method that returns the result anonymously look like?

3 Answers 3

4

For executing SQL Queries that will return results form an known entity, you could use the DataContext.ExecuteQuery method:

IEnumerable<Post> = dataContext.ExecuteQuery<Post>(sqlQuery);

For custom results sets, the Execute method cannot infer and create the anonymous type, but you still can create a class, that contains the fields which are selected in your custom SQL query.

class CustomPostResult  // custom type for the results
{
    public int? PostId { get; set; }
    public DateTime PostedDateUtcTime { get; set; }
}

//...

string sqlQuery = @"SELECT DISTINCT TOP 1 'PostId' = ISNULL(RootPost,Id),
                   PostedDateTimeUtc FROM Post ORDER BY PostedDateTimeUtc DESC";

IEnumerable<CustomPostResult> = dataContext.
                                        ExecuteQuery<CustomPostResult>(sqlQuery);

Check this article:

Sign up to request clarification or add additional context in comments.

Comments

0

I usually dump the results into a List<> of the LINQ object you're using.

List<Post> posts = new List<Post>();

using(your datacontext)
{
  var result = // Your query
  posts = result.ToList():
}

return posts;  

Comments

0

You could try a LINQ expression. Something like this should probably work.

var results = (from post in dc.Posts
               orderby post.PostedDateUtcTime descending
               select new Post
                       {
                           RootPost = (post.RootPost == null) ? post.Id : post.RootPost 
                       }).Distinct<Post>().Take<Post>(1);

I haven't actually ran this, so if anyone finds a problem I'll fix this up.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.