[C#] LINQ插入後可以返回'id'字段嗎?


Answers

插入生成的ID時保存到正在保存的對象的實例中(見下文):

protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
  ProductCategory productCategory = new ProductCategory();
  productCategory.Name = “Sample Category”;
  productCategory.ModifiedDate = DateTime.Now;
  productCategory.rowguid = Guid.NewGuid();
  int id = InsertProductCategory(productCategory);
  lblResult.Text = id.ToString();
}

//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
  ctx.ProductCategories.InsertOnSubmit(productCategory);
  ctx.SubmitChanges();
  return productCategory.ProductCategoryID;
}

參考: http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4 : http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4

Question

當我用Linq-to-SQL將對象輸入到數據庫中時,我可以獲得我剛剛插入的ID,而無需進行其他數據庫調用? 我認為這很容易,我只是不知道如何。