DomainService Delete方法不起作用。为什么?

时间:2012-06-19 15:39:23

标签: c# visual-studio-2010 relational-database

我的问题是:

        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类中使用它。

当然,除非这是一个很大的禁忌。请解释原因,如果是的话。

谢谢!

2 个答案:

答案 0 :(得分: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 :(得分:-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