0
我有以下代碼利用PostSharp自動設置屬性(外鍵),當其導航屬性(用ForeignKeyAttribute標記)設置。如何防止在反序列化期間運行代碼?
反序列化大量實體時代碼非常慢,所以我想知道是否有任何方法可以防止代碼在反序列化期間運行。
該代碼仍然有一些漏洞,我仍在努力,但我在斷開連接的環境中首先使用實體框架代碼,並沒有dbcontext來照顧我。
感謝 克雷格
[Serializable]
public class ForeignKeySynchronisationAttribute : LocationInterceptionAspect
{
public override void OnSetValue(LocationInterceptionArgs args)
{
try
{
var foreignKeyIdSet = false;
var entity = args.Instance;
var propertyInfo = args.Location.PropertyInfo;
if (typeof(BaseEntity).IsAssignableFrom(propertyInfo.PropertyType))
{
// First look for metadata defined ForeignKeyAttribute
var metadata =
entity.GetType()
.GetCustomAttributes(typeof(MetadataTypeAttribute), true)
.OfType<MetadataTypeAttribute>()
.FirstOrDefault();
if (metadata != null)
{
var metadataProperty = metadata.MetadataClassType.GetProperty(propertyInfo.PropertyType.Name);
if (metadataProperty != null)
{
var foreignKeyAttribute = metadataProperty.GetCustomAttributes<ForeignKeyAttribute>().First();
if (foreignKeyAttribute != null)
{
var foreignKeyIdPropertyInfo = entity.GetType().GetProperty(foreignKeyAttribute.Name);
foreignKeyIdPropertyInfo.SetValue(entity, ((BaseEntity)args.Value).PrimaryKey);
foreignKeyIdSet = true;
}
}
}
// Then look for normally defined ForeignKeyAttribute
if (!foreignKeyIdSet)
{
var foreignKeyAttribute = propertyInfo.GetCustomAttributes<ForeignKeyAttribute>().First();
if (foreignKeyAttribute != null)
{
var foreignKeyIdPropertyInfo = entity.GetType().GetProperty(foreignKeyAttribute.Name);
foreignKeyIdPropertyInfo.SetValue(entity, ((BaseEntity)args.Value).PrimaryKey);
}
}
}
}
catch (Exception)
{
throw;
}
finally
{
base.OnSetValue(args);
}
}
}