Program Tip

ID 목록에서 Entity Framework의 여러 행 업데이트

programtip 2020. 10. 26. 08:31
반응형

ID 목록에서 Entity Framework의 여러 행 업데이트


ID 목록을 가져와 관련 필드를 업데이트 할 수있는 엔터티 프레임 워크에 대한 쿼리를 만들려고합니다.

SQL의 예 :

UPDATE Friends
SET msgSentBy = '1234'
WHERE id IN (1, 2, 3, 4)

위의 내용을 엔티티 프레임 워크로 어떻게 변환합니까?


아래와 같이

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
    friends.ForEach(a=>a.msgSentBy='1234');
    db.SaveChanges();
}

최신 정보:

아래와 같이 여러 필드를 업데이트 할 수 있습니다.

friends.ForEach(a =>
                      {
                         a.property1 = value1;
                         a.property2 = value2;
                      });

이를 허용하는 오픈 소스 프로젝트에는 EntityFramework.Extended 및 E ntity Framework Extensions 두 가지가 있습니다 .

참고 URL : https://stackoverflow.com/questions/21592596/update-multiple-rows-in-entity-framework-from-a-list-of-ids

반응형