添加LINQ或DBContext扩展方法以获取元素(如果不存在),然后使用谓词中的数据创建(FirstOrCreate)

Nan*_*oli 5 c# linq extension-methods entity-framework

我正在尝试添加一个LINQ或DbContext扩展方法来获取一个元素(FirstOrDefault),但如果还没有,那么创建一个带有数据的新实例(FirstOrCreate)而不是返回null.

这可能吗?

即:

public static class LINQExtension
{
    public static TSource FirstOrCreate<TSource>(
        this IEnumerable<TSource> source,
        Func<TSource, bool> predicate)
    {
        if (source.First(predicate) != null)
        {
            return source.First(predicate);
        }
        else
        {
            return // ??? 
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

用法可能是:

using (var db = new MsBoxContext())
{
    var status = db.EntitiesStatus.FirstOrCreate(s => s.Name == "Enabled"); 
    //Here we should get the object if we find one
    //and if it doesn't exist create and return a new instance

    db.Entities.Add(new Entity()
    {
         Name = "New Entity",
         Status = status
    });
}
Run Code Online (Sandbox Code Playgroud)

我希望你理解我的方法.

Nan*_*oli 1

结论:最好的解决方案是使用 ?? 代替实现扩展方法 运算符以这种方式:

var status = db.EntitiesStatus.FirstOrDefault(s => s.Name == "Enabled") ?? new EntityStatus(){Name = "Enabled"};
Run Code Online (Sandbox Code Playgroud)