public static class LINQExtension { public static TSource FirstOrCreate<TSource>( this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate, Func<T> defaultValue) { return source.FirstOrDefault(predicate) ?? defaultValue(); } }
Using
var status = db.EntitiesStatus.FirstOrCreate(s => s.Name == "Enabled", () => new EntityStatus {Name = "Enabled"});
However, you should note that this will not work like FirstOrDefault() .
If you have done the following
var listOfStuff = new List<string>() { "Enabled" }; var statuses = from s in listOfStuff select db.EntitiesStatus.FirstOrCreate(s => s.Name == "Enabled", () => new EntityStatus {Name = "Enabled"});
You will get O (n) images in the database.
However, I suspect you did ...
var listOfStuff = new List<string>() { "Enabled" }; var statuses = from s in listOfStuff select db.EntitiesStatus.FirstOrDefault(s => s.Name == "Enabled") ?? new EntityStatus {Name = "Enabled"};
This might probably work ...
source share