[英]Chaining methods in LinqtoSql: How to get entity context
我有一个正在使用的审核库。 我认为这个问题更多地与泛型有关,因为我不确定如何编写与所讨论的方法类似的方法。
我具有以下“链接”方法,似乎无法获取查找表的上下文:
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;
}
}
谢谢!
我只是创建了一个列表,然后在类的oncreate()方法中将每一行添加到列表中。 这些查找表应该在上下文中可用,而我不必创建单独的查找列表(但现在可以100%使用)。 还有其他更好的主意吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.