我的Linq到Sql插入代码似乎工作正常,但我没有在数据库中获得记录

时间:2010-06-09 02:52:12

标签: linq linq-to-sql

这是我的代码。在调试器中,我可以看到代码正在运行。没有错误被抛出。但是,当我回到桌面时,没有插入任何行。我错过了什么?

protected void submitButton_Click(object sender, EventArgs e)
{
    CfdDataClassesDataContext db = new CfdDataClassesDataContext();

    string sOfficeSought = officesSoughtDropDownList.SelectedValue;
    int iOfficeSought;
    Int32.TryParse(sOfficeSought, out iOfficeSought);

    Account act = new Account()
    {
        FirstName = firstNameTextBox.Text,
        MiddleName = middleNamelTextBox.Text,
        LastName = lastNameTextBox.Text,
        Suffix = suffixTextBox.Text,
        CampaignName = campaignNameTextBox.Text,
        Address1 = address1TextBox.Text,
        Address2 = address2TextBox.Text,
        TownCity = townCityTextBox.Text,
        State = stateTextBox.Text,
        ZipCode = zipTextBox.Text,
        Phone = phoneTextBox.Text,
        Fax = faxTextBox.Text,
        PartyAffiliation = partyAfilliatinoTextBox.Text,
        EmailAddress = emailTextBox.Text,
        BankName = bankNameTextBox.Text,
        BankMailingAddress = bankAddressTextBox.Text,
        BankTownCity = bankTownCityTextBox.Text,
        BankState = bankStateTextBox.Text,
        BankZip = bankZipTextBox.Text,
        TreasurerFirstName = treasurerFirstNameTextBox.Text,
        TreasurerMiddleName = treasurerMiddleNamelTextBox.Text,
        TreasurerLastName = treasurerLastNameTextBox.Text,
        TreasurerMailingAddress = treasurerMailingAddressTextBox.Text,
        TreasurerTownCity = treasurerTownCityTextBox.Text,
        TreasurerState = treasurerStateTextBox.Text,
        TreasurerZipCode = treasurerZipTextBox.Text,
        TreasurerPhone = treasurerPhoneTextBox.Text
        //OfficeSought = iOfficeSought
    };
    act.Suffix = suffixTextBox.Text;

    db.SubmitChanges();
}

2 个答案:

答案 0 :(得分:5)

在致电db.SubmitChanges()之前,您还需要一条线(取决于表名称):

db.Accounts.InsertOnSubmit(act);

答案 1 :(得分:0)

您永远不会将新创建的对象添加到数据上下文中。

一般来说,你会称之为:

Db.AddtoAccounts( act );  

该语法适用于EF,但概念是相同的。

您已经分配了一个新对象,但从未告诉数据库上下文您要使用它。

然后调用提交更改。