General way to search or create an object in LINQ to SQL?

Quite often in my LINQ to SQL 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 want to make this a universal method ... Any good ideas?

+3
source share
5 answers

I came up with these extension methods that seem to work well for me.

    public static T FindOrCreate<T>(this Table<T> table, Func<T, bool> find, Action<T> create) where T : class, new()
    {
        T val = table.FirstOrDefault(find);
        if (val == null)
        {
            val = new T();
            create(val);
            table.InsertOnSubmit(val);
        }
        return val;
    }

    public static T FindOrCreate<T>(this Table<T> table, Func<T, bool> find) where T : class, new()
    {
        return FindOrCreate(table, find, a => { });
    }

And it is used like this:

    var invoiceDb = ctx.Invoices.FindOrCreate(a => a.InvoicerId == InvoicerId &&
                                                     a.Number == invoiceNumber);
    invoiceDb.Number = invoiceNumber;

or

    var invoiceDb = ctx.Invoices.FindOrCreate(a => a.InvoicerId == InvoicerId &&
                                                     a.Number == invoiceNumber,
                                              a => a.Number = invoiceNumber);
+2
source

VB.NET Version:

Module dbi
    <System.Runtime.CompilerServices.Extension()> _
    Public Function FindOrCreate( _
        Of T As {Class, New})(ByVal table As Data.Linq.Table(Of T), _
        ByVal find As Func(Of T, Boolean), _
        ByVal create As Action(Of T)) _
        As T

        Dim val As T = table.FirstOrDefault(find)
        If val Is Nothing Then
            val = New T()
            create(val)
            table.InsertOnSubmit(val)
        End If
        Return val
    End Function

    <System.Runtime.CompilerServices.Extension()> _
    Public Function FindOrCreate( _
        Of T As {Class, New})(ByVal table As Data.Linq.Table(Of T), _
        ByVal find As Func(Of T, Boolean)) _
        As T

        Return FindOrCreate(table, find, Function(a))
    End Function

End Module
+2
source

:

public static T FirstOrCreate<T>(this IEnumerable<T> source) where T : class, new()
{
    var result = source.FirstOrDefault();
    return result != null ? result : new T();
}

, , :

public static T FirstOrCreate<T>(this IQueryable<T> source, Expression<Func<T, bool>> predicate) where T : class, new()
{
    var result = source.FirstOrDefault(predicate);
    return result != null ? result : new T();
}

FirstOrDefault() :

Invoice selectedInvoice = (from i in Invoices
                           where i.ID == invoiceID
                           select i).FirstOrCreate();

.. :

Invoice selectedInvoice = db.Invoices.FirstOrCreate(i => i.ID == invoiceID);

, ( ) .

: , , , ( ) DataContext, , :

public static T FirstOrCreate<T>(this IEnumerable<T> source, DataClassesDataContext db) where T : class, new()
{
    var result = source.FirstOrDefault();
    if (result == null)
    {
        result = new T();
        db.GetTable<T>().InsertOnSubmit(result);
    }
    return result;
}

, DataContext , :

Customer selectedCustomer = (from c in db.Customers
                             where c.CustomerId == selectedCustomerId
                             select c).FirstOrCreate(db);

?:)

+1

.

if(invoiceDb == null) ctx.Invoices.InsertOnSubmit(invoiceDB = new Invoice() {Number = invoiceNumber});
0

Null-Coalescing Operator (??)

var invoice = ctx.Invoices.SingleOrDefault(a => a.InvoicerId == InvoicerId &&
                                             a.Number == invoiceNumber) ??
                          new Invoice();
0

Source: https://habr.com/ru/post/1707063/


All Articles