linqpad - SubmitChanges扩展

时间:2011-12-02 11:31:40

标签: linqpad

是否可以在扩展方法中使SubmitChanges()工作?

我目前有这个:

void Main()
{
    // Write code to test your extensions here. Press F5 to compile and run.
    Helper.ConfirmSubmitChanges();
}

public static class Helper
{
    // Write custom extension methods here. They will be available to all queries.
    public static void ConfirmSubmitChanges() 
    { 
        if (MessageBox.Show("Save?", "Do you really want to save all changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            SubmitChanges(); 
        }
    }
}

// You can also define non-static classes, enums, etc.

但是SubmitChanges()在这里已经脱离了上下文。是否有任何我可以通过我的查询传递它将使用此扩展来使其工作?

谢谢, 钢钣

2 个答案:

答案 0 :(得分:2)

您可以通过将当前上下文(this)传递给静态方法来实现:

您的计划:

void Main()
{
    //Do Stuff  
    ConfirmSubmitChanges(this);
}

My Extensions.linq

static void ConfirmSubmitChanges(DataContext context)
{
    if (MessageBox.Show("Submit Changes?", "OK?", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        context.SubmitChanges();
        "Saved".Dump();
    }
}

答案 1 :(得分:1)

如果有人想知道,将“this”传递给Extension。这就是我最终创造的。这很好,因为它也确认了变化的数量。

#region ConfirmSubmitChanges(DataContext dc)
public static void ConfirmSubmitChanges(DataContext dc)
{
    ConfirmSubmitChanges(dc, string.Empty);
}

public static void ConfirmSubmitChanges(DataContext dc, string AdditionalMessage)
{
    ChangeSet set = dc.GetChangeSet();
    var countChanges = 0;
        countChanges += set.Deletes.Count();
        countChanges += set.Inserts.Count();
        countChanges += set.Updates.Count();

    if (countChanges>0) {
        if(!string.IsNullOrEmpty(AdditionalMessage)) { AdditionalMessage = "\n\n(" + AdditionalMessage + ")"; }
        if (MessageBox.Show("Do you really want to save "+ countChanges+" changes?" + AdditionalMessage, "Save all changes?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            dc.SubmitChanges();
        }
    }
}

#endregion