C# .NET4.0 TableAdapter.Update() won't insert new record

邮差的信 提交于 2019-12-24 19:24:13

问题


I have a small application which consists of a DAL, BLL and the Application itself all in different projects under one solution in Visual Studio 2010.

My DAL is using an xsd file to query the database and my BLL has methods to get the information from the DAL and do stuff with it.

Currently I am trying to insert a record using the code behind of the application to make a call to a method in the BLL which then attempts to insert the record by using the Tableadapter.Update() method generated in the xsd file of the DAL.

I can already select and update records with no problem, but I can't insert records.

As far as I know the TableAdapter.Update() method should know to insert a new record if I provide it with a new row, however it is returning a value of 0 - meaning 0 rows were affected, so it isn't working.

The table I am trying to insert into is called tblRoles.

It has an 'ID' column, which is an int, primary key and identity column. It has a 'Name' column which takes nvarchar(50), and it has 4 'CanAdduser' etc columns which take a type of bit.

Here is my code:

APP code behind:

protected void CreateRole(object sender, EventArgs e) {
    RolesBL roles = new RolesBL();

    roles.CreateRole(NewRoleName.Text);

    RolesGridView.DataBind();
}

BLL:

private tblRolesTableAdapter adapter = new tblRolesTableAdapter();

public bool CreateRole(string Name) {
    CMSDS.tblRolesDataTable roles = new CMSDS.tblRolesDataTable();
    CMSDS.tblRolesRow row = roles.NewtblRolesRow();

    row.Name = Name;
    row.CanAddUsers = false;
    row.CanEditUsers = false;
    row.CanSuspendUsers = false;
    row.CanChangeUserPasswords = false;

    int result = adapter.Update(row);

    if(result == 1) {
        return true;
    }

    return false;
}

From what I understand this should insert a new row into the table, but adapter.Update(row) keeps on returning a 0 and I don't know why.

When I debug I can see that all of the row columns have been assigned the correct values, and no errors are thrown.

Any help would be appreciated!

Edit:

I forgot to mention that when I configured the default Fill,GetData() query in the xsd file I did make sure that it auto generated Insert, Update and Delete statements.


回答1:


You haven't added the new Role-Row to the DataTable.

CMSDS.tblRolesDataTable roles = new CMSDS.tblRolesDataTable();
CMSDS.tblRolesRow row = roles.NewtblRolesRow();
row.Name = Name;
roles.AddtblRolesRow(row); 
int result = adapter.Update(roles); //the same as `adapter.Update(row)`


来源:https://stackoverflow.com/questions/6727048/c-sharp-net4-0-tableadapter-update-wont-insert-new-record

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!