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?
@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