简体   繁体   中英

How to get lists of 'id' field after insert in LINQ?

I'm using this code to create dynamically row in Gridview and I'm using LINQ to insert those rows to DB. Now i want to return lists of ID after insert into DB but i don't know how.

Here is my code:

#region [Get List Visitors]
private void GetListVisitors() {
        int rowIndex = 0;
        StringCollection sc = new StringCollection();
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    //extract the TextBox values
                    TextBox visitor_txtName = (TextBox)grdListVisitors.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox visitor_txtAdd = (TextBox)grdListVisitors.Rows[rowIndex].Cells[1].FindControl("txtAdd");
                    //ASPxComboBox visitor_cbxSex = (ASPxComboBox)grdListVisitors.Rows[rowIndex].Cells[1].FindControl("cbxSex");

                    sc.Add(visitor_txtName.Text + "," + visitor_txtAdd.Text);
                    rowIndex++;
                }
                //Store the current data to StringCollection
                AddListVisitors(sc);
            }
}
#endregion

#region [Add List Visitors]
private void AddListVisitors(StringCollection sc)
{
    try {
        List_Visitor add_visitors = new List_Visitor();
        string[] splitItems = null;
        foreach (string item in sc)
        {
            if (item.Contains(","))
            {
                Travel_DBDataContext db = new Travel_DBDataContext();
                splitItems = item.Split(",".ToCharArray());
                add_visitors.Fullname = splitItems[0];
                add_visitors.add = splitItems[1];
                db.List_Visitors.InsertOnSubmit(add_visitors);
                db.SubmitChanges();
            }

        }      
    }
    catch (Exception addvisitors_error) {
        Response.Write(addvisitors_error.Message + "_method addlistvisitor");
    }
}
#endregion

After SubmitChanges has been called, the add_visitors object will contain the primary key of the newly inserted row.

To get all the ids a bit of refactoring is suggested:

// First build an in memory list of objects to add.
var listsToAdd = new List<List_Visitor>();
foreach (string item in sc)
{
  if (item.Contains(","))
  {
    var splitItems = item.Split(",".ToCharArray());

    listsToAdd.Add(new List_Visitor()
    {
      Fullname = splitItems[0],
      add = splitItems[1]
    });
  }
}

// Then add all to the db in one call. Wrap in using block to
// propery dispose of the DataContext and underlying connection.
using(var db = new Travel_DBDataContext())
{
  db.List_Visitors.InsertAllOnSubmit(listsToAdd);
  db.SubmitChanges();
}

// At this point listsToAdd contains all added lists with the generated
// primary key.

As Anders Abel said, once you have called SubmitChanges, the Id will be updated in the objects that have been inserted, but you need to keep a reference to those objects, right now you are using a single object which wont work.

#region [Add List Visitors]
private void AddListVisitors(StringCollection sc)
{
    try {
        var newVisitors = new List<List_Visitor>();
        string[] splitItems = null;
        foreach (string item in sc)
        {
            if (item.Contains(","))
            {
                Travel_DBDataContext db = new Travel_DBDataContext();
                splitItems = item.Split(",".ToCharArray());
                var add_visitors = new List_Visitor();
                add_visitors.Fullname = splitItems[0];
                add_visitors.add = splitItems[1];
                db.List_Visitors.InsertOnSubmit(add_visitors);

                newVisitors.Add(add_visitors);
            }
        }    
        db.SubmitChanges();
        // Now newVisitors will contain a collection of List_Visitor
        // objects with the new Id's in.  
    }
    catch (Exception addvisitors_error) {
        Response.Write(addvisitors_error.Message + "_method addlistvisitor");
    }
}
#endregion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM