开发者

Primary Key Problem ASP.NET

I am developing a career 开发者_运维知识库website for one of my projects. I am using Visual Studio 2010 and ASP.NET Web Forms to code.

My problem is I have got a table named Companies which consists of columns Company ID, Company Name, Company Address and Company Phone. CompanyID is my primary key. I am trying to insert new companies to this table using Linq-to-SQL.

When I execute the following piece of code, if the database is empty, the code works properly but if it is not it can't auto increment the CompanyID and gives me a database error.

How can I solve this issue?

Thanks in advance.

protected void Button1_Click(object sender, EventArgs e)
{
    Label_error.Text = "";
    Page.Validate();

    if (Page.IsValid)
    {
        CareerDataContext db = new CareerDataContext();

        Company newCompany = new Company { coName = TextBox_coName.Text, coAddress = TextBox_coAddress.Text, coPhone = int.Parse(TextBox_coPhone.Text) };
        Company fCompany = db.Companies.SingleOrDefault(company => company.coName.Equals(TextBox_coName.Text));

        if (fCompany == null)
        {
            db.Companies.InsertOnSubmit(newCompany);
            db.SubmitChanges();
        }
        else
            Label_error.Text = "This username is already in use";
    }
}


If your CompanyID is a uniqueidentifier then you can pass in Guid.NewGuid();

For example:

Company newCompany = new Company { coID = Guid.NewGuid(), coName = TextBox_coName.Text, coAddress = TextBox_coAddress.Text, coPhone = int.Parse(TextBox_coPhone.Text) };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜