c# - 使用 DataTable.Load() 而不创建所有列属性

标签 c# .net sql-server

我正在从 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() 函数使用 ColumnNameDataType 初始化表列,但它还会更深入地查看数据库,并添加一些约束,例如AllowDBNullAutoIncrementMaxLength等。

但是,这会导致我的应用程序出现问题,因为我想在内部进一步处理数据。

那么,是否可以仅通过设置最基本的属性(直接来自 select 语句)来执行 Load() ,而不设置 AllowDBNullMaxLength 等等?或者我需要在 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 destination DataTable objects in the DataSet, creating the DataTable objects if they do not already exist. When creating DataTable objects, the Fill operation normally creates only column name metadata. However, if the MissingSchemaAction property is set to AddWithKey, appropriate primary keys and constraints are also created.

我已经测试过它,它只是加载列名称和类型,所有其他属性(例如 AllowDbNullMaxLength)都有其默认值,这些值可能是正确的,也可能是错误的。

关于c# - 使用 DataTable.Load() 而不创建所有列属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31118259/

相关文章:

c# - .Net与Bolt URI的连接失败,但Neo4jClient失败,但Neo4j.Driver失败

c# - "CryptographicException: Cannot find the requested object"证书文件存在

c# - 如何解决这个位操作?

.net - 信任自签名证书以验证服务器(Windows 上的 .NET 客户端)

c# - 什么 C# 数据结构支持以下内容?

c# - 通过 LINQ 查找目标数字是否为数组中两个数字的总和并获取 和 索引

sql-server - Visual Studio : SQL server object explorer error

c++ - 如何使用 SQLConnect 或 SQLDriverConnect

.net - 添加和删​​除多线程应用程序的事件处理程序

sql-server - 合并 SQL Server 中的重复记录