Handy library DelegateDecompiler

Lets assume that we have class with property TestProperty like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public int? BlogId { get; set; }
        public Blog Blog { get; set; }
        [NotMapped]
        [Computed]
        public string TestProperty
        {
            get {
                if (BlogId.HasValue)
                {
                    return Content;
                }
                else {
                    return Title;
                }
            }
        }
    }

We have to mark property with [Computed] [NotMapped] And then assuming that in project EF Core is used we may try to return posts ordered by TestProperty:

1
var result = (db.Posts.OrderBy(p => p.TestProperty)).DecompileAsync().ToList();

As you can see .DecompileAsync() is used which translate property to sql query. If we check this query in SQL Profiler we can see following result:

1
2
3
4
5
6
SELECT [p].[PostId], [p].[BlogId], [p].[Content], [p].[Title]
FROM [Posts] AS [p]
ORDER BY CASE
    WHEN [p].[BlogId] IS NOT NULL THEN [p].[Content]
    ELSE [p].[Title]
END

Installation:
Available on NuGet

More you can read on project page:
https://github.com/hazzik/DelegateDecompiler