简体   繁体   中英

create a static method to access the properties of a list of instance

I create entity classes for the tables of my database. I use Dapper to create lists of the objects when I read multiple records from the database. In my classes I have two non-static methods, InsertStatement and UpdateStatement. They both return the SQL string necessary for Dapper Execute to insert or update the current instance back into the database. I'd like to add a new static method that would return a single SQL Insert statement for all the instances of my objects in my list. Putting it another way, I'd like to create a static method, in the entity class, that can iterate through all the instances of the object in a list and access all the properties for each instance.

Any thoughts?

Ultimately, the returned SQL statement would look something like,

INSERT INTO myTable (property1, property2)
    VALUES ("text1", 5), ("moreText", 27), ("etc.",50), ("etc.",65), ("etc.",1)
using System;
using System.Collections.Generic;
using System.Linq

public class Banana
{
    public int id { get; set; }
    public string name { get; set; }

    public static string GetSql(List<Banana> bananas)
    {
        string _operator = "INSERT INTO bananaTable (id, name) VALUES ";
        string _val = null;

        foreach (var item in bananas)
        {
            _val += $" ({item.id}, '{item.name})'";

            if (item != bananas.Last())
                _val += ", ";
        }

        return _operator + _val + "; ";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM