4imble
4imble

Reputation: 14426

linqpad - SubmitChanges Extension

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

Upvotes: 1

Views: 1263

Answers (2)

4imble
4imble

Reputation: 14426

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

Upvotes: 1

DaveShaw
DaveShaw

Reputation: 52818

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();
    }
}

Upvotes: 2

Related Questions