Entity Framework에서 삽입 된 엔티티의 ID를 얻으려면 어떻게해야합니까? [닫은]
Asp.net의 Entity Framework에 문제가 있습니다. 데이터베이스에 개체를 추가 할 때마다 Id 값을 얻고 싶습니다. 어떻게 할 수 있습니까?
꽤 쉽습니다. 당신이 사용하는 경우 DB는 (같은 ID를 생성 IDENTITY
당신은 단지에 개체를 추가 할 필요가 MS SQL 인치) ObjectSet
와 SaveChanges
관련에 ObjectContext
. Id
자동으로 채워집니다.
using (var context = new MyContext())
{
context.MyEntities.AddObject(myNewObject);
context.SaveChanges();
int id = myNewObject.Id; // Yes it's here
}
기본적으로 엔티티 프레임 워크는 자동 생성 된 s가 사용될 때 각각 INSERT
을 따릅니다 .SELECT SCOPE_IDENTITY()
Id
나는 Entity Framework를 사용할 때 Ids를 성공적으로 검색하기 위해 Ladislav Mrnka의 답변 을 사용하고 있었지만 여기에 게시했습니다. 왜냐하면 그것을 잘못 사용했기 때문에 (즉, 필요하지 않은 곳에서 사용) 여기에 내 결과를 게시 할 것이라고 생각했기 때문입니다. 사람들이 내가 가진 문제를 "해결"하고자하는 경우.
Customer와 외래 키 관계가있는 Order 개체를 고려하십시오. 새로운 고객과 새로운 주문을 동시에 추가했을 때 저는 이와 같은 일을하고있었습니다.
var customer = new Customer(); //no Id yet;
var order = new Order(); //requires Customer.Id to link it to customer;
context.Customers.Add(customer);
context.SaveChanges();//this generates the Id for customer
order.CustomerId = customer.Id;//finally I can set the Id
그러나 제 경우에는 customer.Id와 order.CustomerId 사이에 외래 키 관계가 있었기 때문에 이것이 필요하지 않았습니다.
내가해야 할 일은 이것뿐이었습니다.
var customer = new Customer(); //no Id yet;
var order = new Order{Customer = customer};
context.SaveChanges();//adds customer.Id to customer and the correct CustomerId to order
이제 변경 사항을 저장하면 고객 용으로 생성 된 ID도 주문에 추가됩니다. 추가 단계가 필요하지 않습니다.
나는 이것이 원래 질문에 대한 답이 아니라는 것을 알고 있지만 EF를 처음 접하는 개발자가 필요하지 않은 것에 대해 최고 투표 답변을 과도하게 사용하는 데 도움이 될 것이라고 생각했습니다.
변경 사항을 저장 한 후 엔티티를 다시로드해야합니다. EF에서 추적 할 수없는 데이터베이스 트리거에 의해 변경 되었기 때문입니다. 따라서 DB에서 엔티티를 다시로드해야합니다.
db.Entry(MyNewObject).GetDatabaseValues();
그때
int id = myNewObject.Id;
아래 질문에서 @jayantha 답변을 살펴보십시오.
defaultValue를 사용할 때 Entity Framework에서 삽입 된 엔티티의 ID를 어떻게 얻을 수 있습니까?
아래 질문에서 @christian 대답을 보는 것도 도움이 될 수 있습니다.
이 링크를 참조하십시오.
http://www.ladislavmrnka.com/2011/03/the-bug-in-storegeneratedpattern-fixed-in-vs-2010-sp1/
StoreGeneratedPattern의 속성을 ID로 설정 한 다음 고유 한 코드를 시도해야합니다.
아니면 이것을 사용할 수도 있습니다.
using (var context = new MyContext())
{
context.MyEntities.AddObject(myNewObject);
context.SaveChanges();
int id = myNewObject.Id; // Your Identity column ID
}
The object you're saving should have a correct Id
after propagating changes into database.
You can get ID only after saving, instead you can create a new Guid and assign before saving.
I come across a situation where i need to insert the data in the database & simultaneously require the primary id using entity framework. Solution :
long id;
IGenericQueryRepository<myentityclass, Entityname> InfoBase = null;
try
{
InfoBase = new GenericQueryRepository<myentityclass, Entityname>();
InfoBase.Add(generalinfo);
InfoBase.Context.SaveChanges();
id = entityclassobj.ID;
return id;
}
All answers are very well suited for their own scenarios, what i did different is that i assigned the int PK directly from object (TEntity) that Add() returned to an int variable like this;
using (Entities entities = new Entities())
{
int employeeId = entities.Employee.Add(new Employee
{
EmployeeName = employeeComplexModel.EmployeeName,
EmployeeCreatedDate = DateTime.Now,
EmployeeUpdatedDate = DateTime.Now,
EmployeeStatus = true
}).EmployeeId;
//...use id for other work
}
so instead of creating an entire new object, you just take what you want :)
EDIT For Mr. @GertArnold :
Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;
This will work.
There are two strategies:
Use Database-generated
ID
(int
orGUID
)Cons:
You should perform
SaveChanges()
to get theID
for just saved entities.Pros:
Can use
int
identity.Use client generated
ID
- GUID only.Pros: Minification of
SaveChanges
operations. Able to insert a big graph of new objects per one operation.Cons:
Allowed only for
GUID
When you use EF 6.x code first
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
and initialize a database table, it will put a
(newsequentialid())
inside the table properties under the header Default Value or Binding, allowing the ID to be populated as it is inserted.
The problem is if you create a table and add the
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
part later, future update-databases won't add back the (newsequentialid())
To fix the proper way is to wipe migration, delete database and re-migrate... or you can just add (newsequentialid()) into the table designer.
참고URL : https://stackoverflow.com/questions/5212751/how-can-i-get-id-of-inserted-entity-in-entity-framework
'Nice programing' 카테고리의 다른 글
JavaScript의 "새"키워드가 유해한 것으로 간주됩니까? (0) | 2020.10.03 |
---|---|
C #에서 문자열 앞의 @는 무엇입니까? (0) | 2020.10.03 |
UTF-8로 인코딩 된 NSData를 NSString으로 변환 (0) | 2020.10.03 |
jQuery로 왼쪽과 오른쪽 마우스 클릭을 구별하는 방법 (0) | 2020.10.03 |
Ruby on Rails 데이터베이스 제거 또는 재생성 (0) | 2020.10.03 |