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

1 回答 1

0

请注意,我已经通过不同的方法完成了我所需要的。

干杯

克雷格

于 2013-04-16T06:05:41.797 回答