0
我有一個正在使用的審計庫。我相信這個問題更多的是與泛型有關,因爲我不知道如何編寫類似於所討論的方法。LinqtoSql中的鏈接方法:如何獲取實體上下文
我有以下的「鏈接」的方法似乎並不能得到一個上下文查找表:
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()方法列表中來修復它。這些查找表應該在上下文中可用,我不應該創建一個單獨的查找列表。任何人有任何其他想法?我猜不會? –