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);
}
}
}