我正在使用一个遗留数据库,在这个数据库中,数据被分配了列的最大长度。如果字符串数据较短,则会自动在末尾填充空格。
我想做的是在我所做的每个查询中修剪所有这些结尾空格。
我认为更好的方法之一是使用反射为简洁的查询创建扩展方法。
但我似乎无法让它发挥作用。
父实体:
public class Person: BaseEntity
{
public Identification Identification { get; set; }
public Address Address { get; set; }
public Contact Contact { get; set; }
public Family Family { get; set; }
public ICollection<Payment> Payments { get; set; }
}
子实体示例:
public class Address: BaseEntity
{
public string Street { get; set; }
public int Number { get; set; }
public string BoxNumber { get; set; }
public int ZipCode { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
现在我像这样执行连接查询:
var result = _db.QueryTrim<dynamic>(sql, new { userid = id })
.Select(p => new Person()
{
Identification = IdentificationMapper.MapToIdentificationEntity(p),
Address = AddressMapper.MapToAddressEntity(p)}).First();
我正在尝试实现类似的东西,但我无法让它与查询一起使用
public static class DapperExtensions {
public static IEnumerable<T> Query<T>(this IDbConnection cnn, string sql, object param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null) {
var dapperResult = SqlMapper.Query<T>(cnn, sql, param, transaction, buffered, commandTimeout, commandType);
var result = TrimStrings(dapperResult.ToList());
return result;
}
static IEnumerable<T> TrimStrings<T>(IList<T> objects) {
//todo: create an Attribute that can designate that a property shouldn't be trimmed if we need it
var publicInstanceStringProperties = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => x.PropertyType == typeof (string) && x.CanRead && x.CanWrite);
foreach (var prop in publicInstanceStringProperties) {
foreach (var obj in objects) {
var value = (string) prop.GetValue(obj);
var trimmedValue = value.SafeTrim();
prop.SetValue(obj, trimmedValue);
}
}
return objects;
}
static string SafeTrim(this string source) {
if (source == null) {
return null;
}
return source.Trim();
}
}
最后我想修剪来自数据库的所有字符串。目前我正在对 dapperextension 进行隧道观察,但是否有更好的方法。请告诉我。