2012-09-18 3 views
0

Entity Framework를 사용하여 업데이트하는 방법은 무엇입니까? 업데이트 된 값을 사용하여 객체를 전달하지만 Update 메소드가 표시되지 않습니다.개체를 전달하여 Entity Framwork를 사용하여 업데이트하는 방법

public void UpdateRecipient(Domain.Entities.RecipientEntity recipient) 
    { 
     using (EfDbContext context = CreateEfDbContext(recipient.ApplicationId.ToString())) 
     { 

      context.Recipients. //?? I don't see an update method 
      context.SaveChanges(); 

     } 
    } 

답변

2

세 단계 :

  1. 이 항목이 컨텍스트에서 업데이트 할 가져 오기는 기업에서 업데이트 된 속성을 통해
  2. 복사 당신은 당신의 업데이트 방법
  3. 변경 사항을 저장 전달합니다.

대략 : 업데이트 할 경우

//Retrieve the entity to be updated 
Entity row = context.Recipients.Single(a => a.Id == recipient.Id); 

//Update a column 
row.Name = recipient.Name; 

//Save changes 
context.SaveChanges(); 

/같은 시간에 일을 추가 : 당신이 기록을 갱신하는 경우 다음 당신은 이런 식으로 뭔가를 할 것

using (EfDbContext context = CreateEfDbContext(recipient.ApplicationId.ToString())) 
{ 
    var toUpdate = context.Recipients.SingleOrDefault(r => r.Id == recipient.Id); 
    if (toUpdate != null) 
    { 
     toUpdate.Field1 = recipient.Field1; 
     // Map over any other field data here. 

     context.SaveChanges(); 
    } 
    else 
    { 
     // Handle this case however you see fit. Log an error, throw an error, etc... 
    } 
} 
1

그러면 다음을 수행 할 수 있습니다.

if(!context.Recipients.Any(a => Id == recipient.Id)) 
{ 
    context.Recipients.Add(recipient); 
} 
else 
{ 
    Entity row = context.Recipients.Single(a => a.Id == recipient.Id); 

    row.Name = recipient.Name; 
} 

context.SaveChanges(); 
2

오브젝트를 업데이트하는 또 다른 방법이 있습니다 다시 데이터베이스에서 다시 가져 오기 때문에 데이터베이스에 대한 비용을 절약 할 수 있습니다. 첨부 된 개체는 기본 키 값을 가져야합니다.

  1. 컨텍스트가 '수정'을 국가의
  2. 변경에 업데이트 된 객체를 연결합니다.
  3. 전화 컨텍스트의 SaveChanges() 방법

처럼 :

public void UpdateRecipient(Domain.Entities.RecipientEntity recipient) 
    { 
     using (EfDbContext context = CreateEfDbContext(recipient.ApplicationId.ToString())) 
     { 
      context.Attach(recipient); 
      context.ObjectStateManager.ChangeObjectState(recipient,EntityState.Modified); 
      context.SaveChanges();  
     } 
    } 
관련 문제