Last active
March 6, 2019 23:59
-
-
Save icanhasjonas/0a91ac4698bd6cc7c457cde7b4da2e9d to your computer and use it in GitHub Desktop.
Self Formatting SQLish Filters... for the lazy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[AttributeUsage( AttributeTargets.Property )] | |
public class QueryFilterAttribute : Attribute { | |
public QueryFilterAttribute( string fieldName ) | |
{ | |
FieldName = fieldName; | |
} | |
public QueryFilterAttribute() { } | |
public string FieldName { get; } | |
public string Format( PropertyInfo pi, object instance ) | |
{ | |
var value = pi.GetValue( instance ); | |
switch( value ) { | |
case bool b: return $"{FieldName ?? pi.Name} = {b.ToString().ToLowerInvariant()}"; | |
case null: return null; | |
} | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class QueryFilterFormatter<T> { | |
private static readonly (QueryFilterAttribute queryFilter, PropertyInfo pi)[] _info = typeof(T) | |
.GetProperties( BindingFlags.Instance | BindingFlags.Public ) | |
.Select( x => (queryFilter: x.GetCustomAttribute<QueryFilterAttribute>(), pi: x) ) | |
.Where( x => x.queryFilter != null ) | |
.ToArray(); | |
public static string Format( T instance ) => | |
string.Join( " AND ", _info | |
.Select( x => x.queryFilter.Format( x.pi, instance ) ) | |
.Where( x => x != null ) ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class QueryParams | |
{ | |
[QueryFilter("is_network_notification")] | |
public bool? IsNetworkNotification { get; set; } | |
[QueryFilter("is_published")] | |
public bool? IsPublished { get; set; } | |
[QueryFilter("is_test_account")] | |
public bool? IsTestAccount { get; set; } | |
public override string ToString() => QueryFilterFormatter<QueryParams>.Format(this); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment