Quite often in my LINQ to SQL code, I need to ‘find or create’ an entity as such:
var invoiceDb = ctx.Invoices.FirstOrDefault(a => a.InvoicerId == InvoicerId && a.Number == invoiceNumber); if (invoiceDb == null) { invoiceDb = new Invoice(); invoiceDb.Number = invoiceNumber; ctx.Invoices.InsertOnSubmit(invoiceDb); }
I’m looking to make this a generic method… Any good ideas?
I came up with these extension methods that seems to work well for me.
And it’s used like so:
Or