LINQ to Entities에서 대량 삭제
LINQ 또는 LINQ-to-Entities에서 지정된 쿼리와 일치하는 여러 개체를 대량으로 삭제할 수있는 방법이 있습니까? 내가 찾을 수있는 유일한 참조는 구식이며 제거하려는 모든 개체를 반복하고 수동으로 삭제하는 것은 어리석은 것처럼 보입니다.
질문은 오래된 것입니다 (EF5가 존재하기 전). EF5를 사용하는 모든 사람을 위해 EntityFramework.Extended 는이 작업을 즉시 수행합니다.
얼마 전에 Entity Framework에서 대량 업데이트 (하나의 명령 사용)를 다루는 4 부로 구성된 블로그 시리즈 ( 1 부 , 2 부 , 3 부 및 4 부 )를 작성했습니다.
이 시리즈의 초점은 업데이트 였지만 삭제를 위해 관련된 원칙을 확실히 사용할 수 있습니다.
따라서 다음과 같이 작성할 수 있어야합니다.
var query = from c in ctx.Customers
where c.SalesPerson.Email == "..."
select c;
query.Delete();
해야 할 일은 Delete () 확장 메서드를 구현하는 것뿐입니다. 방법에 대한 힌트는 포스트 시리즈를 참조하십시오.
도움이 되었기를 바랍니다
using (var context = new DatabaseEntities())
{
// delete existing records
context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId);
}
내가 여기서보고있는 답변은 Linq to Sql입니다.
DeleteAllOnSubmit은 System.Data.Linq의 일부이며 Linq to Sql 인 ITable입니다.
Entity Framework에서는이 작업을 수행 할 수 없습니다.
아직 해결책이 없지만 할 때 다시 게시하겠습니다.
EF6를 사용하고 삭제를 위해 행 SQL 쿼리를 실행하려는 경우 :
using (var context = new DatabaseEntities())
{
// delete existing records
context.Database.ExecuteSqlCommand("DELETE FROM YOURTABLE WHERE CustomerID = @id", idParameter);
}
쿼리의 모든 레코드를 삭제하는 데이터 컨텍스트 의 DeleteAllOnSubmit 메서드를 알고 있습니다. 많은 개체가 삭제되고 있으므로 몇 가지 최적화가 있어야합니다. 그래도 잘 모르겠습니다.
얼마나 효율적인지 잘 모르겠지만 다음과 같이 시도해 볼 수 있습니다.
// deletes all "People" with the name "Joe"
var mypeople = from p in myDataContext.People
where p.Name == "Joe";
select p;
myDataContext.People.DeleteAllOnSubmit(mypeople);
myDataContext.SubmitChanges();
당신은 삭제를 수행하고 LINQ에서 호출하는 저장된 proc을 작성할 수 있습니다. 집합 기반 삭제는 전체적으로 더 빠를 수 있지만 너무 많은 레코드에 영향을 미치는 경우 잠금 문제가 발생할 수 있으며 레코드 집합을 통해 반복되는 하이브리드가 필요할 수 있습니다 (한 번에 2000 개, 크기는 데이터베이스 디자인에 따라 다르지만 2000은 집합 기반 delte가 너무 오래 걸리면 테이블의 다른 사용에 영향을 미치므로 삭제를 수행하십시오.
Entity Framework를 통해 데이터를 삭제하려면 DeleteObject 메서드를 사용해야합니다. 삭제할 엔터티 클래스의 EntityCollection 또는 파생 된 ObjectContext에서이 메서드를 호출 할 수 있습니다. 다음은 간단한 예입니다.
NorthwindEntities db = new NorthwindEntities();
IEnumerable<Order_Detail> ods = from o in db.Order_Details
where o.OrderID == 12345
select o;
foreach (Order_Detail od in ods)
db.Order_Details.DeleteObject(od);
db.SaveChanges();
나는 다음과 같이 할 것이다.
var recordsToDelete = (from c in db.Candidates_T where c.MyField == null select c).ToList<Candidates_T>();
if(recordsToDelete.Count > 0)
{
foreach(var record in recordsToDelete)
{
db.Candidate_T.DeleteObject(record);
db.SaveChanges();
}
}
Entity Framework는 엔터티와 함께 작동하고 대부분의 경우 개체 컬렉션을 의미하므로 루프없이 수행 할 수있는 방법이 없다고 생각합니다.
In this example I get the records to delete, and one by one attach them to the results set then request to have them removed. Then I have 1 save changes.
using (BillingDB db = new BillingDB())
{
var recordsToDelete = (from i in db.sales_order_item
where i.sales_order_id == shoppingCartId
select i).ToList<sales_order_item>();
if(recordsToDelete.Count > 0)
{
foreach (var deleteSalesOrderItem in recordsToDelete)
{
db.sales_order_item.Attach(deleteSalesOrderItem);
db.sales_order_item.Remove(deleteSalesOrderItem);
}
db.SaveChanges();
}
}
context.Entity.Where(p => p.col== id)
.ToList().ForEach(p => db.Entity.DeleteObject(p));
these is fastest method to delete record from DB using EF
RemoveRange was introduced in EF6, it can remove a list of objects. Super easy.
var origins= (from po in db.PermitOrigins where po.PermitID == thisPermit.PermitID select po).ToList();
db.PermitOrigins.RemoveRange(origins);
db.SaveChanges();
참고URL : https://stackoverflow.com/questions/869209/bulk-deleting-in-linq-to-entities
'IT박스' 카테고리의 다른 글
Android WebView가 HTTPS URL을로드하지 않음 (0) | 2020.10.11 |
---|---|
"git status"에 내가 master 브랜치에 있고 "git branch"가 새로 생성 된 리포지토리에없는 이유는 무엇입니까? (0) | 2020.10.10 |
명령 줄에서 사용자의 잘리지 않은 Active Directory 그룹 가져 오기 (0) | 2020.10.10 |
Python : 색인 세트를 기반으로 목록에서 하위 집합 선택 (0) | 2020.10.10 |
mysql은 동일한 now ()로 여러 열을 업데이트합니다. (0) | 2020.10.10 |