EF Core - 연결 시나리오에서 데이터 저장하기

해질녘·2022년 2월 8일
0

닷넷 (.NET)

목록 보기
5/12

EF Core: 연결 시나리오에서 데이터 저장하기

https://www.entityframeworktutorial.net/efcore/saving-data-in-connected-scenario-in-ef-core.aspx

위 문서의 발췌 번역입니다.

EF Core는 여러 방법으로 데이터베이스의 데이터에 대해 add, update, delete를 지원한다. 데이터로 스칼라 프로퍼티를 가지고 있는 엔티티는 EntityState에 기반하여 삽입, 수정, 삭제된다.

연결 시나리오와 비연결 시나리오가 있다. 연결 시나리오에서, DbContext 인스턴스 하나가 엔티티 복구와 저장에 쓰인다. 비연결 시나리오와의 차이점이 이 점이다. 이 챕터에서는 연결 시나리오에서 저장을 살펴본다.

아래 그림은 연결 시나리오에서 CUD 작업을 나타내는 그림이다.

그림에서와 같이, 엔티티 프레임워크가 INSERT UPDATE DELETE 문에 대해 명령을 빌드하고 수행한다. 각 엔티티의 EntityStateDbContext.SaveChanges()함수를 통해 변한다. 연결 시나리오에서, DbContext 인스턴스가 모든 엔티티를 추적하고 자동으로 적절한 EntityState가 정해진다.

Insert Data

DbSet.Add, DbContext.Add 메소드 이용. 새로운 엔티티를 컨텍스트에 더한다. SaveChanges() 메소드 호출 시점에 데이터베이스에 새로운 레코드가 삽입된다.

using (var context = new SchoolContext())
{
    var std = new Student()
    {
        FirstName = "Bill",
        LastName = "Gates"
    };
    context.Students.Add(std);

    // or
    // context.Add<Student>(std);

    context.SaveChanges();
}

위 예시에서 context.Students.Add(std)Student 엔티티의 새롭게 생성된 인스턴스를 더한다. 주석 처리된 context.Add<Student>(std) 역시 같은 역할.

Updating Data

연결 시나리오에서, EF Core API가 모든 엔티티를 추적한다. 그래서 내가 어떤 엔티티 데이터를 수정하면, EF가 자동으로 EntityStateModified로 변경한다. 이는 SaveChanges()호출 시 데이터베이스에 반영된다.

using (var context = new SchoolContext())
{
    var std = context.Students.First<Student>(); 
    std.FirstName = "Steve";
    context.SaveChanges();
}

Deleting Data

DbSet.Remove() 혹은 DbContext.Remove 이용

using (var context = new SchoolContext())
{
    var std = context.Students.First<Student>();
    context.Students.Remove(std);

    // or
    // context.Remove<Student>(std);

    context.SaveChanges();
}
profile
해질녘 | 백엔드 공부 중

0개의 댓글