sqlkata / querybuilder

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird
https://sqlkata.com
MIT License
3.09k stars 499 forks source link

some usefull extensions that helps write code faster #713

Closed nester-a closed 3 months ago

nester-a commented 6 months ago

Hi Added a few methods that speed up development using SqlKata.

ahmad-moussawi commented 6 months ago

@nester-a could you provide more details about this PR?

nester-a commented 6 months ago

@nester-a could you provide more details about this PR?

I've added three methods.

1 is Select<T>() that allows you to not pass a list of columns to be fetched. Ex:

class Post
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Date CreatedAt  { get; set; }
}

//before
new Query("Posts").Select("Id", "Title", "CreatedAt").Get<Post>();

//method I added
new Query("Posts").Select<Post>().Get<Post>();

2 and 3 are Insert<T>() and it async version InsertAsync<T>() that allows you do not pass enumerable of columns and values then you need insert many rows Ex:

class Product
{
    public string Name { get; set; }
    public decimal Price{ get; set; }
}

//before
var cols = new [] {"Name", "Price"};

var data = new [] {
    new object[] { "A", 1000 },
    new object[] { "B", 2000 },
    new object[] { "C", 3000 },
};

db.Query("Products").Insert(cols, data);

//method I added
var data = new List<Product>()
{
    new(){ Name = "A",  Price = 1000 },
    new() { Name = "B",  Price = 2000 },
    new(){ Name = "C",  Price = 3000 }
}

db.Query("Products").Insert(data);

Select<T>() and Insert<T>() use reflection to derive property names and use them as column names

fairking commented 5 months ago

@nester-a Do you use data annotations for column and table names? https://stackoverflow.com/questions/56993920/reflect-table-column-names-based-on-data-annotation

Sometimes I use such annotation when my columns do not reflect the reality.

ahmad-moussawi commented 3 months ago

Thanks for the suggestion, and I'm sorry for the late reply; I feel such features are incomplete and may create confusion for developers (with ORM usage). Better to create a separate package for this.

In the future if we decided to go through this path, we might need to think in all possible cases first (like joins/updates/insert) etc...