C#中从数据库加载信息的问题
这就是我正在尝试做的事情。我有一个正在使用代码读取的数据库:
OleDbCommand command;
command = new OleDbCommand("SELECT " + Student.ID + " FROM " + newStudent.DataFile, conn);
conn.Open();
dt.Load(command.ExecuteReader());
conn.Close();
然后我将数据表绑定到 datagridview 并显示表的内容。现在的问题是,我有更多信息要添加到不在数据表 dt 中的信息数据库。例如,我有一个名为 Grade 的学生对象字段,该字段在数据文件中找不到,但由用户输入并存储在学生对象的属性中。
有没有一种方法可以将查询结果加载到列表中,以便我可以用另一种方法手动为数据表创建行和列,然后添加列表的内容(包含 id)和成绩信息,而不是将查询结果加载到数据表中手动在学生对象中?
This is what i am trying to do. I have a database that i am reading from using the code:
OleDbCommand command;
command = new OleDbCommand("SELECT " + Student.ID + " FROM " + newStudent.DataFile, conn);
conn.Open();
dt.Load(command.ExecuteReader());
conn.Close();
I then have the datatable bind to a datagridview and display the contents of the table.Now the problem is, i have more information to add to the datatable dt that is not in the database. For example, i have a field for the student object called Grade that is not found in the datafile but entered in by the user and stored in a property for the student object.
Instead of loading the query result into a datatable, is there a way to load it into a list so i can manually create rows and columns for a datatable in another method and then add the contents of the list(containing id) and the grade information in the student object manually?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不喜欢像 @Bas 建议的那样使用完整的 ORM 框架...
请查看 ToTable 方法可在数据表的数据视图上使用。您只需使用 DataTable.DefaultView 即可获取数据表的 DataView:
或者,您可以将要附加的其他数据加载到第二个数据表中,并使用 DataTable.Merge Method
编辑:为了考虑要添加其他列,您可以更改上面的列表建议,如下所示:
If you don't fancy going for a full blown ORM framework such as the one @Bas has suggested...
Take a look at the ToTable method available from on a Datatable's Dataview. You can get the DataView for your Datatable simply using DataTable.DefaultView:
Alternatively, you can load the additional data you want to append into a second datatable, and use the DataTable.Merge Method
EDIT: To account for wanting to add additional columns, you can change the above list suggestion as follows:
您可以使用实体框架从数据库中提取对象模型。之后,您可以将成绩属性添加到您的对象(因为这些对象是在 部分类)。这提供了一种(很大程度上)更加结构化/易于使用的方式来向数据结构添加自定义逻辑和属性。
您可以使用与使用传统 ADO.NET 类似的方式将 GUI 组件绑定到实体框架对象。
You could use Entity Framework to extract an object model from your database. Afterwards you could add the property for grade to your object (due to the fact that these objects are created in partial classes). This provides a (vastly) more structured / easy to use way of adding custom logic and attributes to your data structure.
You can bind your GUI components to entity framework objects in a similar way as you would using conventional ADO.NET.