对象相关问题 [英] Objects related Problem

查看:66
本文介绍了对象相关问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在sqlServer中有一个或多个表。我想从数据库中获取数据并将此表的数据保存到像类这样的对象中,但我不想将这些数据保存到数据集中。有什么方法可以将数据保存到从数据库中获取数据的对象中?如何将数据传递到对象而不是数据集或数据表?

I have a table or tables in sqlServer. I want to take data from database and keep this table''s data into objects like class, but I dont want to keep this data into dataset. What are those ways to keep data into objects taking data from database? How can I pass data into object but not in dataset or datatable?

推荐答案

有一种方法..创建实体类具有与表列相同的属性,然后从SqlDataReader中的数据库中检索数据,然后遍历SqlDataReader,创建一个实体类对象,将每列的值分配给对象的各种属性,并在List中添加对象。



例如//假设我的表只包含两个字段姓名和地址

There is one way.. create entity class having property same like your table columns,
then retrieve data from database in SqlDataReader, then traverse through the SqlDataReader, create an object of entity class assingn the value of each column to rispective property of your object and add the object in List.

eg // assume my table contains only two fields Name and Address
Public Class Student
{
  Public string Name
 {
  get;
  set;
 }
 Public string Address
 {
  get;
  set;
 }
 
 Public List<student> GetAllData()
 {
  List<student> lstStudent = new List<student>();
  //here code to fetch data from database
  While(reader.Read())
  {
     Student obj = new Student();
     obj.Name = reader["Name"].ToString();
     Obj.Address = reader["Address"].ToString();
     lstStudent.Add(obj);
  }
  return lstStudent;
 }
}
</student></student></student>



如果解决方案对您有帮助你接受解决方案


If the solution is helpful to you the accept the solution


public class exampleObject

{

public string Column1FromTablex {get; set;}

public string Column2FromTabley {get;设置;}

...

}



//然后你可以使用SQLCommand执行查询数据库

//然后你可以遍历结果并构建对象

//例如:从Example1.dbo.Tablex中选择column1 ...并使用查询以准确获取exampleObject所需的列
public class exampleObject
{
public string Column1FromTablex {get; set;}
public string Column2FromTabley {get; set;}
...
}

//Then you can use SQLCommand to execute query against database
//Then you can iterate through the results and build the objects
//Ex: "Select column1 From Example1.dbo.Tablex..." and use the query to get exactly the columns you want for your "exampleObject"


这篇关于对象相关问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆