将数据库行插入 XML/XSD class C#

Inserting rows of database into XML/XSD class C#

总结:我使用 xsd.exe 从 xml 模板创建了一个 class。假设有一个名为 human 的 class 具有两个属性:name(string) 和 id(int)。我的 table,人类,有两列名为 name 和 id。我正在尝试使用 SqlDataReader 读取数据库的行并为每一行创建一个人类对象。有没有比这更聪明的方法将每一列插入到我的一个属性中?否则,我将需要许多 'if' 语句来检查每一行的名称并将其与属性相关联。

XML Class
 public partial class human
    {

        private string name;

        private int id;

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public string name
        {
            get
            {
                return this.nameField;
            }
            set
            {
                this.nameField = value;
            }
        }

        /// <remarks/>
        [System.Xml.Serialization.XmlAttributeAttribute()]
        public int id
        {
            get
            {
                return this.idField;
            }
            set
            {
                this.idField = value;
            }
        }
    }

** 这是在使用 SqlConnection

与我的数据库建立连接之后
SqlCommand cmd = new SqlCommand("SELECT * FROM tablename");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
   //Iterating through the columns of a specific row
   for (int i = 0; i < reader.FieldCount; i++) 
   {
       human human1 = new human();
       string currentColValue = reader[i].ToString();
       string currentColName = reader.GetName(i);
       if (currentColName == "name" ) { human.name = currentColValue; }
       else { human.id = (int) currentColValue; } //Now you know it's the other attribute
       //Now you insert the human into a larger class or array
   }
}

如您所见,使用两列 table 相对容易。但是,如果我有一个包含多个列的 table,那么它就变得更难了。有更简单的方法吗?

NHibernate 似乎是可行的方法,但它的学习曲线似乎相当陡峭 - 有人介意给我一些示例代码吗?

我决定使用 PetoPoco,而不是像 NHibernate 和 Entity Framework 那样使用完整的 ORM(对象关系映射)。在我看来,通过 NHibernate 学习起来要容易得多,因为它是一个简单的 class 文件。

与其采用 n 列的 n 个 if 语句的解决方案,它只用了一行代码!

IEnumerable<human> humanList = (new PetaPoco.Database(connectionstring))
.Fetch<human>("SELECT * FROM dbTable");