C# 我可以在 LINQ 插入后返回“id”字段吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/113928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 14:22:27  来源:igfitidea点击:

Can I return the 'id' field after a LINQ insert?

提问by naspinski

When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how.

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

采纳答案by Germstorm

After you commit your object into the db the object receives a value in its ID field.

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

So:

所以:

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;

回答by Jason Stevenson

When inserting the generated ID is saved into the instance of the object being saved (see below):

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

reference: 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

回答by Khalid Salameh

Try this:

尝试这个:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;