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

问题描述 投票:178回答:3

当我使用Linq-to SQL将对象输入到数据库中时,是否可以获取刚插入的ID而不进行另一次数据库调用?我假设这很容易,我只是不知道如何。

c# .net linq linq-to-sql
3个回答
263
投票

将对象提交到db后,对象在其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;

15
投票

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


0
投票

试试这个:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;
© www.soinside.com 2019 - 2024. All rights reserved.