Sql标识列(ID)在插入时不递增

时间:2014-06-19 21:34:08

标签: c# asp.net sql sql-server

我在现有SQL数据库中创建了一个新表来保存上传的文件。每行都插入零作为ID。它没有递增。我究竟做错了什么? 更新: BTW我在发布之前就研究了这个。我搜索了SO(这里)并用Google搜索。我没有找到任何解释或解决我的问题,我不想让我的帖子混乱(现在我有):(。

表结构是这样的:

Table: tblFileUploads
Columns: 
  ID int not null (PK, IDENTITY 1,1)
  Name nvarchar (100)
  ContentType varchar(50)
  Size bigint
  Data varbinary(max)
  FirmID int

存储过程(根据收到的评论更新 - 但仍未设置ID)

ALTER PROCEDURE [dbo].[InsertUploadedFiles] 
    -- Add the parameters for the stored procedure here
    @Name nvarchar(100),
    @ContentType varchar(50),
    @Size bigint,
    @Data varbinary(max),
    @FirmId int 
AS
BEGIN

    SET NOCOUNT ON;

    INSERT INTO dbo.tblFileUploads (Name, ContentType, Size, Data, FirmID)
    VALUES (@Name, @ContentType, @Size, @Data, @FirmId)

END

要插入sql的aspx.cs代码:

public void InsertFile ( string filename, string contentType, int size, byte[]data)
    {
        //create new sqlconnection
        using (SqlConnection Sqlcon = new SqlConnection(GetConnectionString()))
        {
            using (SqlCommand cmdInsertFile  = new SqlCommand())
            {
                try
                {
                    //firm exists  
                    if (HttpContext.Current.Session["ActiveFirmId"] != null)
                    {
                        OpenConnection(Sqlcon);
                        //Sqlcon.Open();

                        //Insert tblFileUploads
                        cmdInsertFile.Connection = Sqlcon;
                        cmdInsertFile.CommandTimeout = 0;
                        cmdInsertFile.CommandType = CommandType.StoredProcedure;
                        cmdInsertFile.CommandText = "InsertUploadedFiles";                     

                        //Filename
                        cmdInsertFile.Parameters.Add(new SqlParameter("@Name", SqlDbType.NVarChar,100));
                        cmdInsertFile.Parameters["@Name"].Value = filename;

                        //Content Type
                        cmdInsertFile.Parameters.Add(new SqlParameter("@ContentType", SqlDbType.VarChar,50));
                        cmdInsertFile.Parameters["@ContentType"].Value = contentType;

                        //Size
                        cmdInsertFile.Parameters.Add(new SqlParameter("@Size", SqlDbType.Int));
                        cmdInsertFile.Parameters["@Size"].Value = size;

                        //Data
                        cmdInsertFile.Parameters.Add(new SqlParameter("@Data", SqlDbType.VarBinary));
                        cmdInsertFile.Parameters["@Data"].Value = data;//DBNull.value;

                        //FirmId
                        cmdInsertFile.Parameters.Add(new System.Data.SqlClient.SqlParameter("@FirmId", System.Data.SqlDbType.Int, 4, System.Data.ParameterDirection.Input, false, ((System.Byte)(0)), ((System.Byte)(0)), "FirmId", System.Data.DataRowVersion.Original, null));
                        cmdInsertFile.Parameters["@FirmId"].Value = HttpContext.Current.Session["ActiveFirmId"].ToString();

                        cmdInsertFile.ExecuteNonQuery();

                        Sqlcon.Close();
                    }

                    //new firm
                    else
                    {
                        Label lblWarning = new Label();
                        lblWarning.Text = "Please Save new firm before you may upload their application documents.";
                    }

                }//end try

              catch (SqlException sqlEx)
                {
                    WriteToEventLog("SqlException Message: " + sqlEx.Message + ", " + sqlEx.Source + ", " + sqlEx.LineNumber);
                }//end of catch

            }//end of 2nd using

        }//end of 1st using

    }//end of method

更新:在上传按钮点击时检索值的代码。我认为这是我的SQL问题的无关紧要,因为数据被捕获和插入,它是不起作用的标识列。

   protected void btnUploadFile_Click(object sender, EventArgs e)
    {

        //check file extension
        Boolean fileOK = false;

        if (FileUpload1.HasFile)
        {            
                //Verify that file to upload is PDF format
                string fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

                string[] allowedExtensions = {".pdf"};

                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (fileExtension == allowedExtensions[i])
                    {
                        fileOK = true;
                    }
                    else
                    {
                    Label1.Text = "Cannot accept files of this type. Please scan document to PDF and try upload again.";
                    }
                }
            }//end if (hasfile)
        else
        {
            Label1.Text = "You have not specified a file.";
        } //end else

        if (fileOK)
        {
            try
            {

                HttpFileCollection files = Request.Files;

                foreach (string fileTagName in files)
                {
                    HttpPostedFile file = Request.Files[fileTagName];
                    if (file.ContentLength > 0)
                    {

                        int size = file.ContentLength;

                        string name = file.FileName;

                        int position = name.LastIndexOf("\\");

                        name = name.Substring(position + 1);

                        string contentType = file.ContentType;

                        byte[] fileData = new byte[size];

                        file.InputStream.Read(fileData, 0, size);

//pass to database
                        SqlConnLib inserter = new SqlConnLib();
                        inserter.InsertFile(name, contentType, size, fileData);
                    }
                }
            }//try

            catch (Exception ex)
            {
                //Display failure message
                Label1.Text = "ERROR Message: " + ex.Message.ToString() +
                    ", <br />Source:  " + ex.Source +
                    ", <br />TargetSite: " + ex.TargetSite +
                    ", <br />StackTrace: " + ex.StackTrace;
            } //end catch 
        }//if

        }//end method

2 个答案:

答案 0 :(得分:2)

您的表格没有使用ID的标识字段,或者您的数据未被插入(这听起来不像是这样。)

您应该展开表格目录,然后展开“按键”键。为你想要的桌子。你应该在那里看到你的身份栏。双击键,然后转到列属性,它应该是allow nulls = no,默认值=空白,type = int,标识规范是,(在标识规范下)是identity = yes,identity increment = 1,identity种子= 1

如果这些不是真实的陈述,那么你没有正确地创建身份,你应该从表中重新开始。

create table database.dbo.demo
(
    id int not null identity(1, 1)
, name nvarchar(100)
, contenttype varchar(50)
, size bigint
, data varbinary(max)
, firmid int
)

insert into database.dbo.demo (name, contenttype, size, data, firmid)
select name, contenttype, size, data, firmid from database.dbo.oldtable

答案 1 :(得分:1)

我认为可以解决存储过程中的匹配字段。

ALTER PROCEDURE [dbo].[InsertUploadedFiles] 

    @Name nvarchar(100),
    @ContentType varchar(50),
    @Size bigint,
    @Data varbinary,
    @FirmId int 
AS
BEGIN

    SET NOCOUNT ON;

    INSERT INTO tblFileUploads (Name,ContentType,Size,Data,FirmId)
    VALUES (@Name, @ContentType, @Size, @Data, @FirmId)

END