Когда я вводю объект в БД с помощью Linq-to-SQL, могу ли я получить только что вставленный идентификатор без повторного вызова БД? Я предполагаю, что это довольно легко, я просто не знаю как.
После фиксации вашего объекта в БД объект получает значение в своем поле 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;
При вставке сгенерированного идентификатора сохраняется в экземпляр сохраняемого объекта (см. Ниже):
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
Попробуйте это:
MyContext Context = new MyContext(); Context.YourEntity.Add(obj); Context.SaveChanges(); int ID = obj._ID;