:
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);
?:)