Skip to content

Commit 47d63be

Browse files
author
Harish
committed
add select by type
1 parent 981f444 commit 47d63be

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

QueryBuilder.Tests/SelectTests.cs

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -958,5 +958,35 @@ public void SelectWithExists_OmitSelectIsFalse()
958958
Assert.Equal("SELECT * FROM [Posts] WHERE EXISTS (SELECT [Id] FROM [Comments] WHERE [Comments].[PostId] = [Posts].[Id])", sqlServer.ToString());
959959
}
960960

961+
public record Post(int Id, string Title, DateTime Published);
962+
963+
[Fact]
964+
public void SelectType() {
965+
var q = new Query("Post").Select<Post>();
966+
967+
var pgsql = Compilers.CompileFor(EngineCodes.PostgreSql, q);
968+
969+
Assert.Equal("""
970+
SELECT "Id", "Title", "Published" FROM "Post"
971+
""", pgsql.ToString());
972+
}
973+
974+
public class Comment {
975+
[Column("comment_id")] public int Id { get; set; }
976+
[Column("post_id")] public int PostId { get; set; }
977+
[Column("content")] public string Content { get; set; }
978+
[Column("created_at")] public DateTime Created { get; set; }
979+
}
980+
981+
[Fact]
982+
public void SelectType_WithColumnAttribute() {
983+
var q = new Query("Comment").Select<Comment>();
984+
985+
var pgsql = Compilers.CompileFor(EngineCodes.PostgreSql, q);
986+
987+
Assert.Equal("""
988+
SELECT "comment_id" AS "Id", "post_id" AS "PostId", "content" AS "Content", "created_at" AS "Created" FROM "Comment"
989+
""", pgsql.ToString());
990+
}
961991
}
962992
}

QueryBuilder/Query.Select.cs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Linq;
4+
using System.Reflection;
45

56
namespace SqlKata
67
{
@@ -117,5 +118,24 @@ public Query SelectMax(string column, Func<Query, Query> filter = null)
117118
{
118119
return SelectAggregate("max", column, filter);
119120
}
121+
122+
public Query Select<T>() {
123+
var properties = typeof(T).GetProperties();
124+
var columns = new List<string>();
125+
foreach (var property in properties) {
126+
if (property.GetSetMethod() == null) {
127+
continue;
128+
}
129+
130+
var name = property.Name;
131+
var attribute = property.GetCustomAttribute<ColumnAttribute>();
132+
if (attribute != null) {
133+
name = $"{attribute.Name} as {name}";
134+
}
135+
136+
columns.Add(name);
137+
}
138+
return Select(columns);
139+
}
120140
}
121141
}

0 commit comments

Comments
 (0)