Programming

LINQ 삽입 후 'id'필드를 반환 할 수 있습니까?

procodes 2020. 5. 19. 20:50
반응형

LINQ 삽입 후 'id'필드를 반환 할 수 있습니까?


Linq-to-SQL을 사용하여 DB에 객체를 입력하면 다른 DB 호출을하지 않고도 방금 삽입 한 ID를 얻을 수 있습니까? 나는 이것이 매우 쉽다고 가정하고, 나는 단지 방법을 모른다.


객체를 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;

생성 된 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;

참고 URL : https://stackoverflow.com/questions/113928/can-i-return-the-id-field-after-a-linq-insert

반응형