我正在从 SQL Server 数据库加载数据,如下所示:
SqlCommand cmd = new SqlCommand("select * from x", conn);
cmd.CommandType = CommandType.Text;
DataTable dt = new DataTable();
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd, LoadOption.PreserveChanges);
问题:
Load()
函数使用 ColumnName
和 DataType
初始化表列,但它还会更深入地查看数据库,并添加一些约束,例如AllowDBNull
、AutoIncrement
、MaxLength
等。
但是,这会导致我的应用程序出现问题,因为我想在内部进一步处理数据。
那么,是否可以仅通过设置最基本的属性(直接来自 select
语句)来执行 Load()
,而不设置 AllowDBNull
、MaxLength
等等?或者我需要在 Load() 之后清除这些值吗?或者还有另一种方法可以调用 Load()
吗?
最佳答案
如果您不希望出现这种行为,请不要使用 DataTable.Load
但是DbDataAdapter.Fill(DataTable)
:
DataTable dt = new DataTable();
using(var da = new SqlDataAdapter("select * from x", conn))
da.Fill(dt);
The
Fill
operation then adds the rows to destinationDataTable
objects in theDataSet
, creating theDataTable
objects if they do not already exist. When creatingDataTable
objects, theFill
operation normally creates only column name metadata. However, if theMissingSchemaAction
property is set toAddWithKey
, appropriate primary keys and constraints are also created.
我已经测试过它,它只是加载列名称和类型,所有其他属性(例如 AllowDbNull
或 MaxLength
)都有其默认值,这些值可能是正确的,也可能是错误的。
关于c# - 使用 DataTable.Load() 而不创建所有列属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31118259/