IQueryable to return a single record

entity-framework-core iqueryable linq

Question

I am using EF Core and am attempting to create a query provider which accepts any type and a single value. I then want to run a query to return the FirstOrDefault of the passed in items which have the selected property set to the passed in value. something similar to this:

public class TagPicker<T>
{
    public IQueryable<T> Pick(IQueryable<T> source, string column, string filter)
    {
        T result = source.FirstOrDefault(r => r.column == value);

        if (result is null)
        {
            return new T { column = filter };
        }
        else {
            return result;
        }
    }
}

I have several types which will need this type of query performed. I am trying to avoid having to create duplicates of this type of query for each type.

Any ideas?

1
0
8/3/2019 8:54:33 PM

Popular Answer

@PanagiotisKanavos commented a simple solution for doing this. Here it is slightly modified:

Object.Foo = context.Foos.FirstOrDefault(x => x.Property == form.Value) ?? new Foo { Property = form.Value };

Hope this helps someone

0
6/29/2018 9:55:18 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow