调用DataAdapter填充的ASP.NET会创建重复的条目

时间:2015-08-31 16:18:39

标签: c# asp.net sql-server

这种奇怪的行为今天开始了:

代码非常简单:(C#4.5)

bool connOpened = OpenConnectiontoDB();

SqlCommand cmdCounties = new SqlCommand("spGetCounties", cn);
       cmdCounties.CommandType = CommandType.StoredProcedure;

       DataSet dsCounties = new DataSet();

       SqlDataAdapter da = new SqlDataAdapter();
       da.SelectCommand = cmdCounties;

       try
       {
           da.Fill(dsCounties);

       }

如果我直接运行存储过程spGetCounties(在DB中),我会得到单个值:

ALTER PROCEDURE [dbo].[spGetCounties]

AS
BEGIN   
    SET NOCOUNT ON;
    SELECT c.tblCountyName,c.tblCountyID
    FROM
    tblCounty c
    ORDER BY 
    c.tblCountyName asc
END

tblCounty不包含任何重复值。

如果我运行C#代码,我会查看我看到的dsCounties的值

A
A
B
B
C
C   
...

我在page_load事件中调用存储过程。

  DataSet dsCounties = new DataSet();
                dsCounties = busLayer.GetCounties();

但是当我查看数据库层代码时,这并不重要,dsCounty的值为null,并且只要da.Fill(dsCounties)运行,我就会在dsCounties中看到重复的值。

============================================

更新: 浪费了2个小时的时间并试图减少代码并将其与以前的版本进行比较后,我意识到这种行为是由于其他人的简单但愚蠢的错误。

1:新开发人员将Dev端配置文件更改为指向Production DB !!!

2:我们光荣的数据库管理员将每行复制两次到生产!!!我无法想象这会如何发生并忘记将County_ID作为主键。

对不起,如果这个问题浪费了你的时间。

1 个答案:

答案 0 :(得分:1)

在页面加载方法中,它将在每次加载页面时添加数据。 你需要添加

if(!PostBack)
{
     DataSet dsCounties = new DataSet();
     dsCounties = busLayer.GetCounties();
}

如果它的回发,则表示之前已加载。如果不是,则需要初始化数据集。