我有一个正在使用的审计库。我相信这个问题更多地与泛型有关,因为我不确定如何编写与所讨论的方法类似的方法。
我有以下“链接”方法,似乎无法获取查找表的上下文:
AuditProperty(m => m.StationTypeId)
.GetValueFrom(stationtypeId => GetStationType(stationtypeId))
.WithPropertyName("StationType");
这个想法是将一个 ID 传递给 GetValueFrom() linq 方法,并从(在这种情况下)stationtype 表中返回一个字符串。我已经通过在运行时将静态表分配给实际的 Stationtype 表(下面是 stationTypeTable)来使其工作,因此我可以执行如下查找:
public string GetStationType(int? stationTypeID)
{
var stationtype = stationTypeTable.FirstOrDefault(st => object.Equals(st.Id, stationTypeID));
return stationtype != null ? stationtype.Value : String.Empty;
}
我知道这是不好的做法。当某些主键 ID 不存在时,我遇到了异常。但是,当我调用 linq 方法时,我实际上似乎无法获得任何表的上下文。知道如何正确地做到这一点吗?linq 方法如下供您参考:
public class EntityAuditConfiguration<TEntity> : EntityAuditConfiguration
{
/// <summary>
/// Customize the default behavior when auditing a specific property
/// </summary>
public CustomPropertyAuditor<TEntity, T> AuditProperty<T>(Expression<Func<TEntity, T>> propertySelector)
{
var config = new CustomPropertyAuditor<TEntity, T>();
CustomizedProperties.Add(propertySelector.ToPropertyInfo(), config);
return config;
}
/// <summary>
/// Include an association (relationship) table to audit along with the parent table
/// </summary>
public RelatationshipConfiguration<TChildEntity, TEntity> AuditMany<TChildEntity>(Expression<Func<TEntity, IEnumerable<TChildEntity>>> selector)
where TChildEntity : class
{
var relationship = new RelatationshipConfiguration<TChildEntity, TEntity>();
((IEntityAuditConfiguration) this).Relationships.Add(relationship);
return relationship;
}
}
public class CustomPropertyAuditor<TEntity, TProp> : IPropertyAuditor
{
private Expression<Func<TProp, string>> _propertySelector;
private string _propertyName;
public CustomPropertyAuditor<TEntity, TProp> WithPropertyName(string propertyName)
{
if (propertyName == null) throw new ArgumentNullException("propertyName");
_propertyName = propertyName;
return this;
}
public CustomPropertyAuditor<TEntity, TProp> GetValueFrom(Expression<Func<TProp, string>> valueSelector)
{
if (valueSelector == null) throw new ArgumentNullException("valueSelector");
_propertySelector = valueSelector;
return this;
}
AuditedProperty IPropertyAuditor.AuditProperty(PropertyInfo property, object oldValue, object newValue)
{
var auditedProperty = new AuditedProperty(_propertyName ?? property.Name);
var func = _propertySelector.Compile();
if (oldValue != null)
auditedProperty.OldValue = func.DynamicInvoke(oldValue).ToString();
if (newValue != null)
auditedProperty.NewValue = func.DynamicInvoke(newValue).ToString();
return auditedProperty;
}
}
谢谢!