1

这就是我想要做的。我有一个使用代码读取的数据库:

OleDbCommand command;
command = new OleDbCommand("SELECT " + Student.ID + " FROM " + newStudent.DataFile, conn);
conn.Open();
dt.Load(command.ExecuteReader());
conn.Close();

然后我将数据表绑定到 datagridview 并显示表的内容。现在的问题是,我有更多信息要添加到不在数据库中的数据表 dt 中。例如,我有一个名为 Grade 的学生对象字段,该字段在数据文件中找不到,但由用户输入并存储在学生对象的属性中。

不是将查询结果加载到数据表中,有没有办法将其加载到列表中,这样我就可以用另一种方法手动为数据表创建行和列,然后添加列表的内容(包含 id)和等级信息在学生对象中手动?

4

2 回答 2

0

如果您不喜欢使用完整的 ORM 框架,例如 @Bas 建议的框架...

查看 Datatable 的 Dataview 中可用的ToTable方法。您可以简单地使用 DataTable.DefaultView 为您的 Datatable 获取 DataView:

List<Long> myList = dt.DefaultDataView.ToTable(True, "ID").AsEnumerable().ToList()
myList.Add(1234)
//etc

或者,您可以将要附加的其他数据加载到第二个数据表中,并使用DataTable.Merge 方法

编辑:要考虑添加其他列,您可以更改上述列表建议,如下所示:

// Create a class to hold the information you want to bind, 
// you could use anonymous types if preferred
class MyDataRow
{
    public long ID { get; set; }
    public string AnotherColumn { get; set; }
    public string AndAnotherColumn { get; set; }
}

// then later on when creating that list use something along the lines of:
List<MyDataRow> myList = dt.DefaultDataView.ToTable(True, "ID").AsEnumerable().Select(x => new MyDataRow { ID = x.ID }).ToList()
// you now have a list of MyDataRow which you can work with
// for example...
if (myList.Any())
    myList.First().AnotherColumn = "foo";

// as an exmaple of using an anoymous type (not my preference, but an option nonetheless)
var anonymousList = dt.DefaultDataView.ToTable(True, "ID").AsEnumerable().Select(x => new { ID = x.ID, whateverYouWantToCallIt = "some other data but this is read only property" }).ToList()
// you can work with the anonymous list in much the same way, it just isn't explicitly declared
// and the properties are Read Only
if (anonymousList.Any())
    Console.WriteLine(anonymousList.First().whateverYouWantToCallIt);
于 2011-06-23T14:54:02.520 回答
0

您可以使用实体框架从数据库中提取对象模型。之后,您可以将等级属性添加到您的对象(因为这些对象是在部分类中创建的)。这提供了一种(非常)更加结构化/易于使用的方式,可以将自定义逻辑和属性添加到您的数据结构中。

您可以使用与使用传统 ADO.NET 类似的方式将 GUI 组件绑定到实体框架对象。

于 2011-06-23T14:46:42.877 回答