2012-06-19 108 views
0

我的問題是這樣的:DomainService刪除方法不起作用。爲什麼?

 Inspections 
      InspectionItems 

在我的關係型數據庫,我需要「級聯」刪除,使得沒有多餘的數據周圍鋪設。例如,如果我刪除了檢查,還需要刪除所有相關項目。

我寫的代碼到域服務類:

 public void IDInspectionDelete(string id) 
     { 
      var inspections = from a in ObjectContext.Inspections 
           where a.ID == new Guid(id) 
           select a; 
      foreach (Inspection inspection in inspections) 
      { 
       var items = from a in ObjectContext.InspectionItems 
          where a.InspectionID == inspection.ID 
          select a; 
       foreach (InspectionItem item in items) 
       { 
        DeleteInspectionItem(item); 
       } 
       DeleteInspection(inspection); 
      } 
     } 

然後在我的視圖模型我調用該函數:

 context.IDInspectionDelete(id_string); 

...這什麼都不做。完全一樣。不是窺視。代碼將逐步通過,沒有錯誤等,但沒有刪除。我打算將它重新寫入我的視圖模型中,並致電

context.Remove(item) 

這應該起作用。但我想在DomainService類中使用它。

除非,當然,這是一個很大的禁忌。請解釋爲什麼,如果是的話。

謝謝!

+0

我看不到任何承諾或上下文提交更改。 –

+0

我會讓你的viewmodel像通常那樣去除父檢查記錄。在您的域服務中,自定義行爲以包含子記錄的級聯刪除。吃點你的蛋糕吧。 –

+0

@SteveB啊是的,對不起 - 我也叫context.SubmitChanges(); – xhedgepigx

回答

0

解決方案對這個問題做這一切在使用ObjectContext的域服務類如此;

域服務類

[Invoke] 
public bool DeleteInspection(Guid ID) 
{ 
    bool bResult = false; 

    // get the inspection to delete 
    Inspection inspection = this.ObjectContext.Inspections.Where(a=>a.ID == ID).FirstOrDefualt(); 

    // first delete all attached entities 
    foreach (InspectionItem item in inspection.Items) 
    { 
     this.ObjectContext.DeleteObject(item); 
    } 

    // save changes 
    this.ObjectContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); 

    // then delete item itself 
    this.ObjectContext.DeleteObject(inspection); 

    // set result to true only if at least one record has been effected 
    if (this.ObjectContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave) >0) 
     bResult = true; 

    return bResult;   
} 

視圖模型

context.DeleteInspection(InspectionID, io => 
{ 
    if (io.Value) 
     MessageBox.Show("Inspection successfully deleted"); 
}, null); 
-1

一個選項是使用SQL觸發數據庫表,以便級聯刪除與應用程序根本沒有關係。這意味着我可以撥打context.Remove(item),數據庫將通過刪除進行級聯。

以防萬一它是有用的人,我會把我的SQL以及:

SQL

ALTER TRIGGER [dbo].[InspectionDeleteTrigger] 
    ON [dbo].[Inspection] 
    INSTEAD OF DELETE 
AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 
    SET NOCOUNT ON; 

    -- Delete ALL Items Linked to deleted Inspection -- 
    DELETE FROM InspectionItem 
    FROM InspectionItem AS tbl JOIN deleted AS d ON tbl.InspectionID = d.ID 

    -- Delete current Inspection -- 
    DELETE FROM Inspection 
    FROM Inspection AS tbl JOIN deleted AS d ON tbl.ID = d.ID 

END 
相關問題