How about using an extension method like so:
public static T FirstOrCreate<T>(this IEnumerable<T> source) where T : class, new()
{
var result = source.FirstOrDefault();
return result != null ? result : new T();
}
If you want it to be able to accept a predicate, you can use this definition:
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();
}
That way you can use it in place of FirstOrDefault() like so:
Invoice selectedInvoice = (from i in Invoices
where i.ID == invoiceID
select i).FirstOrCreate();
..or with the use of a Predicate:
Invoice selectedInvoice = db.Invoices.FirstOrCreate(i => i.ID == invoiceID);
Will either return a matching entity or a new (non-null) entity instead.
Edit: I've been thinking about this today, and I occurs to me that the above will require you to detect that the entity is new (not existing) and attach it to the DataContext, so I came up with this compromise, using the same approach:
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;
}
The drawback is you have to pass the DataContext in as a parameter, but it should work nicely enough:
Customer selectedCustomer = (from c in db.Customers
where c.CustomerId == selectedCustomerId
select c).FirstOrCreate(db);
Surely one upvote is out there? :)