예제 #1
0
        /// <summary>
        /// 自动处理对象子级的新数据引用关系
        /// </summary>
        /// <typeparam name="T">类型参数T</typeparam>
        /// <param name="ctx">上下文</param>
        /// <param name="t">类型实例</param>
        public static void AddNewNavigationData <T>(this DbContext ctx, T t) where T : class, IEntitySet
        {
            ctx.Save(t);

            var properties = typeof(T).GetProperties().Where(x => x.PropertyType.IsFromType(typeof(IEnumerable <IEntitySet>))).ToList();

            if (properties.IsNotNullOrEmpty())
            {
                foreach (var prop in properties)
                {
                    var values = prop.GetValue(t) as IEnumerable <object>;
                    if (values.IsNotNullOrEmpty())
                    {
                        var type       = values.FirstOrDefault().GetType();
                        var foreignKey = type.GetForeignKey <T>();
                        var property   = type.GetProperty(foreignKey);
                        if (property != null)
                        {
                            foreach (var value in values)
                            {
                                ctx.AddNewAttachmentData(value);
                                property.SetValue(value, t.Id);
                                ctx.Save(value);
                            }
                        }
                    }
                }
            }
        }