在DataTable中加载DataReader时获取约束异常 [英] Getting a constraints exception when loading a DataReader in a DataTable

查看:186
本文介绍了在DataTable中加载DataReader时获取约束异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用以下c#代码从合并中返回输出的SQL2008数据库运行合并查询:

I run a Merge query against a SQL2008 db that returns the output from the merge using the following c# code:

cmd.CommandText = query;
if (conn.DBConn.State == ConnectionState.Closed) conn.DBConn.Open();
DbDataReader dbReader = cmd.ExecuteReader();
DataTable dt = new DataTable("Results");
dt.Load(dbReader);

最后一行抛出错误:


System.Data.ConstraintException-无法启用约束。多一行或
包含违反非null,唯一或外键
约束的值。

System.Data.ConstraintException - Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.

我在MSDN上找到了 ,并且适合我的情况,但是我该如何解决呢?

I found this on MSDN, and it fits my scenario, but how do I actually fix this?

使用 dt.PrimaryKey = null; 清除主键。不起作用

Clearing the primary key with dt.PrimaryKey=null; does not work

上面的代码将用于许多表。

The code above will be used for many tables.

推荐答案

对于该错误,我发现的最简单的解决方法是将其仅包装在Catch块中,然后忽略该错误。我在实施cjb110的优秀文章的更多内容时发现了它有关约束错误的信息。令我惊讶的是,我偶然得知,我们可以完全忽略该错误并按原样使用数据表。我已经验证了下面的VB代码(可以通过C#语法的代码转换器自由运行)至少按预期返回了所有行和列,至少在遇到问题的情况下(在我的情况下

The simplest workaround I've found for this error is to merely wrap it in a Catch block and ignore the error. I discovered it while implementing cjb110's excellent article on digging up more information about the constraint errors. To my surprise, I learned by sheer accident that we can ignore the error altogether and use the datatable as-is. I've verified that the VB code below (feel free to run it through a code converter for C# syntax) returns all of the rows and columns as expected, at least in the instances I've encountered the problem (which in my case have been mainly on ADOMD Command objects).

 Try

 TempDataTable.Load(PrimaryCommand.ExecuteReader)

Catch ex As ConstraintException

  End Try

请注意,此问题可能是较新线程 DataTable.Load,一或多个行包含违反非null的值

Note that this question is a probable duplicate of a newer thread DataTable.Load, One or more rows contain values violating non-null

这篇关于在DataTable中加载DataReader时获取约束异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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