Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions QueryBuilder.Tests/SelectTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -958,5 +958,35 @@ public void SelectWithExists_OmitSelectIsFalse()
Assert.Equal("SELECT * FROM [Posts] WHERE EXISTS (SELECT [Id] FROM [Comments] WHERE [Comments].[PostId] = [Posts].[Id])", sqlServer.ToString());
}

public record Post(int Id, string Title, DateTime Published);

[Fact]
public void SelectType() {
var q = new Query("Post").Select<Post>();

var pgsql = Compilers.CompileFor(EngineCodes.PostgreSql, q);

Assert.Equal("""
SELECT "Id", "Title", "Published" FROM "Post"
""", pgsql.ToString());
Comment on lines +964 to +971
}

public class Comment {
[Column("comment_id")] public int Id { get; set; }
[Column("post_id")] public int PostId { get; set; }
[Column("content")] public string Content { get; set; }
[Column("created_at")] public DateTime Created { get; set; }
}

[Fact]
public void SelectType_WithColumnAttribute() {
var q = new Query("Comment").Select<Comment>();

var pgsql = Compilers.CompileFor(EngineCodes.PostgreSql, q);

Assert.Equal("""
SELECT "comment_id" AS "Id", "post_id" AS "PostId", "content" AS "Content", "created_at" AS "Created" FROM "Comment"
""", pgsql.ToString());
}
}
}
20 changes: 20 additions & 0 deletions QueryBuilder/Query.Select.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace SqlKata
{
Expand Down Expand Up @@ -117,5 +118,24 @@ public Query SelectMax(string column, Func<Query, Query> filter = null)
{
return SelectAggregate("max", column, filter);
}

public Query Select<T>() where T : class {
var properties = typeof(T).GetProperties();
var columns = new List<string>();
Comment on lines +122 to +124
foreach (var property in properties) {
if (property.GetSetMethod() == null) {
continue;
}
Comment on lines +125 to +128

var name = property.Name;
var attribute = property.GetCustomAttribute<ColumnAttribute>();
if (attribute != null) {
name = $"{attribute.Name} as {name}";
}

columns.Add(name);
}
Comment on lines +122 to +137
return Select(columns);
}
}
}