Files

100 lines
3.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using xCommons.Extensions;
using xModels.Base;
namespace xDataService.Extensions {
public static class EntityExtensions {
/// <summary>
/// return all values of an entity properties as a json string ...
/// </summary>
/// <param name="item"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static string GetPropValues<T> (this T item)
where T : XBaseEntity<T> {
//
var props = item.GetType ().GetProperties ();
var vals = props.Select (p => p.GetValue (item));
//
return vals.ToJSON ();
}
/// <summary>
/// check values of all properties of an Entity contains specific value or not ...
/// </summary>
/// <param name="item"></param>
/// <param name="value"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static bool PropValuesContains<T> (this T item, string value)
where T : XBaseEntity<T> => item.GetPropValues ()
.ToNormalString ()
.Contains (value);
/// <summary>
/// Retrieve Default Column Map of specific Entity ...
/// </summary>
/// <param name="item"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static IDictionary<string, Expression<Func<T, object>>> GetDefaultColumnsMap<T> (this T item)
where T : XBaseEntity<T> {
//
if (item.IsNull ()) {
return null;
}
//
var result = new Dictionary<string, Expression<Func<T, object>>> ();
var props = item.GetType ().GetProperties ();
//
foreach (var prop in props) {
result.Add (
prop.Name,
t => t.GetType ().GetProperty (prop.Name).GetValue (t, null));
}
//
return result;
}
/// <summary>
/// Check a Type is XBaseEntity or not ...
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static bool IsXEntity(this Type source)
{
//
var result = !source.IsNull();
if (!result)
{
return result;
}
//
var baseType = source.BaseType;
while(!baseType.IsNull() && baseType != typeof(object))
{
//
if (baseType.IsGenericType &&
baseType.GetGenericTypeDefinition() == typeof(XBaseEntity<>))
{
result = true;
break;
}
//
baseType = baseType.BaseType;
}
//
return result;
}
}
}