linqpad - SubmitChanges Extension

大城市里の小女人 提交于 2019-12-08 05:57:49

问题


Is it possible to get SubmitChanges() to work from within an extension method?

I currently have this:

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.

But SubmitChanges() is out of context here. Is there anything that i can pass it from my queries that will use this extension to make it work?

Thanks, Kohan


回答1:


You can do it with the by passing the current Context (this) into the static method:

Your program:

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

In My Extensions.linq:

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



回答2:


In case anyone wants to know, after passing "this" to the Extension. This is what i created in the end. It's nice because it also confirms the number of changes.

#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


来源:https://stackoverflow.com/questions/8355686/linqpad-submitchanges-extension

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!