创建一个静态方法来访问实例列表的属性
create a static method to access the properties of a list of instance
我为我的数据库表创建实体 classes。当我从数据库中读取多条记录时,我使用 Dapper 创建对象列表。在我的 classes 中,我有两个非静态方法,InsertStatement 和 UpdateStatement。它们都 return Dapper Execute 将当前实例插入或更新回数据库所必需的 SQL 字符串。我想添加一个新的静态方法,该方法将 return 单个 SQL Insert 语句用于我列表中所有对象的实例。换句话说,我想在实体 class 中创建一个静态方法,它可以遍历列表中对象的所有实例并访问每个实例的所有属性。
有什么想法吗?
最终,returned SQL 语句看起来像,
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 + "; ";
}
}
我为我的数据库表创建实体 classes。当我从数据库中读取多条记录时,我使用 Dapper 创建对象列表。在我的 classes 中,我有两个非静态方法,InsertStatement 和 UpdateStatement。它们都 return Dapper Execute 将当前实例插入或更新回数据库所必需的 SQL 字符串。我想添加一个新的静态方法,该方法将 return 单个 SQL Insert 语句用于我列表中所有对象的实例。换句话说,我想在实体 class 中创建一个静态方法,它可以遍历列表中对象的所有实例并访问每个实例的所有属性。
有什么想法吗?
最终,returned SQL 语句看起来像,
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 + "; ";
}
}