我可以在LINQ插入后返回" id"字段吗?

时间:2020-03-06 14:31:52  来源:igfitidea点击:

当我使用Linq-to-SQL将对象输入数据库时​​,是否可以获取我刚刚插入的ID,而无需进行其他数据库调用?我以为这很简单,我只是不知道怎么做。

解决方案

将对象提交到数据库后,该对象将在其ID字段中收到一个值。

所以:

myObject.Field1 = "value";

// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();

// You can retrieve the id from the object
int id = myObject.ID;

插入时,将生成的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