我的函数有时会将数据插入到DB中,有时也不会

时间:2017-04-04 19:24:47

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

我正在开发一个Web表单,我希望将与特定用户相关的文档上传到文件夹中,并在MySql服务器数据库中为其创建相应的条目。现在每当我提交文档的详细信息时,它都会上传文档,但有时它会跳过数据库中的条目。

代码段1

protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
    String path = Server.MapPath("~/AdminUploads/");
    if (FileUpload1.HasFile)
    {
        Response.Write(FileUpload1.FileName);
        try
        {
            FileUpload1.SaveAs(path + FileUpload1.FileName);
            DOCUPLOADED doc = new DOCUPLOADED();
            doc.DOCTYPE = Int32.Parse(DropDownList2.SelectedValue);
            doc.DOCID = TextBox4.Text;
            doc.FILEPATH = path + FileUpload1.FileName;
            doc.FORUSER = Int64.Parse(TextBox5.Text);
            doc.FILENAME = TextBox6.Text;

            uploaddoc ud = new uploaddoc(doc);

            if (ud.upload())
            {
                Response.Write("<script>alert('Addition succesfull');<script>");
            }
            else
            {
                Response.Write("<script>alert('Fatal error : addition unsuccesfull');</script>");
            }
        }
        catch (Exception ex)
        {
            Response.Write("<script>alert('Error : File was not uploaded ');</script>");
        }
    }

代码段2

public class uploaddoc
{
    private DOCUPLOADED doc;
    public uploaddoc(DOCUPLOADED doc)
    {
        this.doc = doc;
    }
    public bool upload()
    {
        if (doc != null)
        {
            dbcfDataContext dc = new dbcfDataContext();
            dc.DOCUPLOADEDs.InsertOnSubmit(doc);
            try
            {
                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                //
            }
            return true;
        }
        else
            return false;
    }
}

ID应该是自动增量的,你可以看到1-6缺席,所以是9 10等。

ID is supposed to be autoincremented,you can see 1-6 are absent,so are 9 10 etc

dbcfdatacontext是通过创建dbml文件并将表拖到其上来完成与数据库的连接。

1 个答案:

答案 0 :(得分:0)

我修复了你的代码:

public class uploaddoc
{
    private DOCUPLOADED doc;
    public uploaddoc(DOCUPLOADED doc)
    {
        this.doc = doc;
    }
    public bool upload()
    {
        if (doc != null)
        {
            dbcfDataContext dc = new dbcfDataContext();
            dc.DOCUPLOADEDs.InsertOnSubmit(doc);
            //try
            //{
                dc.SubmitChanges();
            //}
            //catch (Exception ex)
            //{
                //
            //}
            return true;
        }
        else
            return false;
    }
}

但严肃地说,空挡块相当于用脚射击自己。不要那样做。