Ejemplo n.º 1
0
 public FilteredCollection(ICollection <TEntity> collection, DbCollectionEntry dbCollectionEntry)
 {
     _filter            = entity => !entity.Deleted;
     _dbCollectionEntry = dbCollectionEntry;
     _compiledFilter    = _filter.Compile();
     _collection        = collection != null?collection.Where(_compiledFilter).ToList() : null;
 }
Ejemplo n.º 2
0
        public void DeleteRegion(Region region)
        {
            foreach (Territory territory in this.ChangeSet.GetAssociatedChanges(region, p => p.Territories, ChangeOperation.Delete))
            {
                Territory origTerrigory = this.ChangeSet.GetOriginal(territory);
                if (origTerrigory != null)
                {
                    this.DbContext.Territories.AttachAsModified(territory, origTerrigory, this.DbContext);
                }
                else
                {
                    this.DbContext.Territories.Attach(territory);
                }

                // need to remove any employee territory rows
                DbEntityEntry     tEntityEntry        = this.DbContext.Entry(territory);
                DbCollectionEntry employeesCollection = tEntityEntry.Collection("Employees");
                employeesCollection.Load();
                territory.Employees.Clear();

                this.DbContext.Territories.Remove(territory);
            }

            DbEntityEntry <Region> entityEntry = this.DbContext.Entry(region);

            if (entityEntry.State != EntityState.Detached)
            {
                entityEntry.State = EntityState.Deleted;
            }
            else
            {
                this.DbContext.Regions.Attach(region);
                this.DbContext.Regions.Remove(region);
            }
        }
Ejemplo n.º 3
0
        private static void ShowRacersExplicitLoading()
        {
            using (var data = new Formula1Entities())
            {
                // data.RaceResults.Load();
                foreach (var racer in data.Racers)
                {
                    Console.WriteLine("{0} {1}", racer.FirstName, racer.LastName);

                    DbCollectionEntry entry = data.Entry(racer).Collection("RaceResults");
                    if (!entry.IsLoaded)
                    {
                        entry.Load();
                    }
                    DbCollectionEntry <Racer, RaceResult> entry1 = data.Entry(racer).Collection(r => r.RaceResults);
                    if (!entry1.IsLoaded)
                    {
                        entry1.Load();
                    }

                    //if (!data.Entry(racer).Collection("RaceResults").IsLoaded)
                    //{
                    //  data.Entry(racer).Collection("RaceResults").Load();
                    //}
                    foreach (var raceResult in racer.RaceResults)
                    {
                        Console.WriteLine("\t{0} {1:d} {2}", raceResult.Race.Circuit.Name,
                                          raceResult.Race.Date, raceResult.Position);
                    }
                }
            }
        }
        public FilteredCollection(ICollection <T> collection, DbCollectionEntry collectionEntry, Expression <Func <T, Boolean> > filter)

        {
            this.Filter = filter;

            this.collection = collection ?? new HashSet <T>();

            this.collectionEntry = collectionEntry;

            this.compiledFilter = filter.Compile();

            if (collection != null)
            {
                foreach (var entity in collection)
                {
                    this.collection.Add(entity);
                }
                this.collectionEntry.CurrentValue = this;
            }

            else
            {
                this.LoadIfNecessary();
            }
        }
Ejemplo n.º 5
0
        public virtual void RemoveFromParent <P>(int parentId, T entity) where P : class
        {
            DbSet <P> parentSet = context.Set <P>();
            P         parent    = parentSet.Find(parentId);

            if (parent == null)
            {
                throw new Exception("Non-existent Parent Entity.");
            }
            if (parent is BaseDocument)
            {
                if ((parent as BaseDocument).sys_active == false)
                {
                    throw new Exception("Non-existent Parent Entity.");
                }
            }

            string navigationPropertyName = typeof(T).Name + "s";

            DbCollectionEntry <P, T> childrenCollection = context.Entry(parent).Collection <T>(navigationPropertyName);

            childrenCollection.Load();

            if (childrenCollection.CurrentValue.Contains(entity))
            {
                childrenCollection.CurrentValue.Remove(entity);
                context.SaveChanges();
            }
        }
Ejemplo n.º 6
0
        public IQueryable <TRelation> LoadQuery <TRelation>(Expression <Func <TEntity, ICollection <TRelation> > > accessor)
            where TRelation : class
        {
            DbEntityEntry <TEntity> entry = context.Entry(entity);
            DbCollectionEntry <TEntity, TRelation> collection = entry.Collection(accessor);

            return(collection.Query());
        }
Ejemplo n.º 7
0
 internal ComBoostEntityCollection(DbEntityEntry owner, IEntityContext <T> context, DbCollectionEntry navigation, IQueryable <T> queryable, int count)
 {
     _Entry         = owner;
     _Navigation    = navigation;
     _Context       = context;
     InnerQueryable = queryable;
     Count          = count;
 }
Ejemplo n.º 8
0
        public virtual async Task LoadCollectionAsync <TProperty>(TEntity entity, Expression <Func <TEntity, ICollection <TProperty> > > childs, CancellationToken cancellationToken, bool forceReload = false) where TProperty : class
        {
            DbCollectionEntry <TEntity, TProperty> collection = _dbContext.Entry(entity).Collection(childs);

            if (forceReload == true || collection.IsLoaded == false)
            {
                await collection.LoadAsync(cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 9
0
        public virtual void LoadCollection <TProperty>(TEntity entity, Expression <Func <TEntity, ICollection <TProperty> > > childs, bool forceReload = false) where TProperty : class
        {
            DbCollectionEntry <TEntity, TProperty> collection = _dbContext.Entry(entity).Collection(childs);

            if (forceReload == true || collection.IsLoaded == false)
            {
                collection.Load();
            }
        }
Ejemplo n.º 10
0
        public void Load <TRelation>(Expression <Func <TEntity, ICollection <TRelation> > > accessor)
            where TRelation : class
        {
            DbEntityEntry <TEntity> entry      = context.Entry(entity);
            DbCollectionEntry       collection = entry.Collection(accessor);

            if (!collection.IsLoaded)
            {
                collection.Load();
            }
        }
Ejemplo n.º 11
0
 public static void Filter <TParentEntity, TCollectionEntity>(this DbContext context, String navigationProperty, Expression <Func <TCollectionEntity, Boolean> > filter)
     where TParentEntity : class, new()
     where TCollectionEntity : class
 {
     (context as IObjectContextAdapter).ObjectContext.ObjectMaterialized += delegate(Object sender, ObjectMaterializedEventArgs e)
     {
         if (e.Entity is TParentEntity)
         {
             DbCollectionEntry col = context.Entry(e.Entity).Collection(navigationProperty);
             col.CurrentValue = new FilteredCollection <TCollectionEntity>(null, col, filter);
         }
     };
 }
Ejemplo n.º 12
0
        public virtual void LoadCollection <TProperty>(TEntity entity, Expression <Func <TEntity, IEnumerable <TProperty> > > childs)
            where TProperty : class
        {
            Expression <Func <TEntity, ICollection <TProperty> > > convertedChilds = Expression.Lambda <Func <TEntity, ICollection <TProperty> > >(childs.Body, childs.Parameters);

            Attach(entity);

            DbCollectionEntry <TEntity, TProperty> collection = _dbContext.Entry(entity).Collection(convertedChilds);

            if (collection.IsLoaded == false)
            {
                collection.Load();
            }
        }
Ejemplo n.º 13
0
        public virtual async Task LoadCollectionAsync <TProperty>(TEntity entity, Expression <Func <TEntity, IEnumerable <TProperty> > > childs, CancellationToken cancellationToken)
            where TProperty : class
        {
            Expression <Func <TEntity, ICollection <TProperty> > > convertedChilds = Expression.Lambda <Func <TEntity, ICollection <TProperty> > >(childs.Body, childs.Parameters);

            Attach(entity);

            DbCollectionEntry <TEntity, TProperty> collection = _dbContext.Entry(entity).Collection(convertedChilds);

            if (collection.IsLoaded == false)
            {
                await collection.LoadAsync(cancellationToken).ConfigureAwait(false);
            }
        }
Ejemplo n.º 14
0
        public void RemoveFromParent <P>(int parentId, T entity) where P : class
        {
            DbSet <P> parentSet = context.Set <P>();
            P         parent    = parentSet.Find(parentId);

            if (parent == null)
            {
                throw new Exception("Non-existent Parent Entity.");
            }
            if (parent is BaseDocument)
            {
                if ((parent as BaseDocument).sys_active == false)
                {
                    throw new Exception("Non-existent Parent Entity.");
                }
            }

            string navigationPropertyName = typeof(T).Name + "s";

            DbCollectionEntry <P, T> childrenCollection = context.Entry(parent).Collection <T>(navigationPropertyName);

            childrenCollection.Load();

            if (childrenCollection.CurrentValue.Contains(entity))
            {
                childrenCollection.CurrentValue.Remove(entity);
                context.SaveChanges();

                /*DOCUMENT*/
                if (typeof(T).IsSubclassOf(typeof(BaseDocument)))
                {
                    var document = entity as BaseDocument;

                    document.InfoTrack = context.Set <Track>()
                                         .AsNoTracking()
                                         .FirstOrDefault(t => t.Entity_ID == document.id && t.Entity_Kind == document.AAA_EntityName);

                    if (document.InfoTrack != null)
                    {
                        document.InfoTrack.User_LastEditedByKey = byUserId;
                        document.InfoTrack.Date_EditedOn        = DateTime.Now;

                        context.Entry(document.InfoTrack).State = EntityState.Modified;
                    }

                    context.SaveChanges();
                }
            }
        }
Ejemplo n.º 15
0
        public void Load <TRelation>(Expression <Func <TEntity, ICollection <TRelation> > > accessor)
            where TRelation : class
        {
            Func <TEntity, bool> isLoaded = e =>
            {
                DbEntityEntry <TEntity> entry = context.Entry(e);
                DbCollectionEntry <TEntity, TRelation> collection = entry.Collection(accessor);
                return(collection.IsLoaded);
            };
            Expression <Func <TEntity, bool> > expression = getFilterExpression(isLoaded);

            if (expression == null)
            {
                return;
            }
            context.Set <TEntity>()
            .Where(expression)
            .Select(accessor)
            .Load();
        }
Ejemplo n.º 16
0
        public override void RemoveFromParent <P>(int parentId, T document)
        {
            DbSet <P> parentSet = context.Set <P>();
            P         parent    = parentSet.Find(parentId);

            if (parent == null)
            {
                throw new Exception("Non-existent Parent Entity.");
            }
            if (parent is BaseDocument)
            {
                if ((parent as BaseDocument).sys_active == false)
                {
                    throw new Exception("Non-existent Parent Entity.");
                }
            }

            string navigationPropertyName = typeof(T).Name + "s";

            DbCollectionEntry <P, T> childrenCollection = context.Entry(parent).Collection <T>(navigationPropertyName);

            childrenCollection.Load();

            if (childrenCollection.CurrentValue.Contains(document))
            {
                childrenCollection.CurrentValue.Remove(document);
                context.SaveChanges();

                context.Entry(document).Reference(e => e.InfoTrack).Load();

                if (document.InfoTrack != null)
                {
                    document.InfoTrack.User_LastEditedByKey = ByUserId;
                    document.InfoTrack.Date_EditedOn        = DateTimeOffset.Now;

                    context.Entry(document.InfoTrack).State = EntityState.Modified;
                }

                context.SaveChanges();
            }
        }
Ejemplo n.º 17
0
 private void RegisterCollectionPropertyFilter()
 {
     (this as IObjectContextAdapter).ObjectContext.ObjectMaterialized +=
         delegate(Object sender, ObjectMaterializedEventArgs e)
     {
         if (e.Entity is Entity)
         {
             var entityType = e.Entity.GetType();
             IEnumerable <PropertyInfo> collectionProperties;
             if (!CollectionPropertiesPerType.TryGetValue(entityType, out collectionProperties))
             {
                 CollectionPropertiesPerType[entityType] = (collectionProperties = entityType.GetProperties()
                                                                                   .Where(p => p.PropertyType.IsGenericType && typeof(ICollection <>) == p.PropertyType.GetGenericTypeDefinition()));
             }
             foreach (var collectionProperty in collectionProperties)
             {
                 var collectionType = typeof(FilteredCollection <>).MakeGenericType(collectionProperty.PropertyType.GetGenericArguments());
                 DbCollectionEntry dbCollectionEntry = Entry(e.Entity).Collection(collectionProperty.Name);
                 dbCollectionEntry.CurrentValue = Activator.CreateInstance(collectionType, new[] { dbCollectionEntry.CurrentValue, dbCollectionEntry });
             }
         }
     };
 }
Ejemplo n.º 18
0
 public WrapperDbCollectionEntry(DbCollectionEntry <TEntity, TElement> inner)
 {
     this.inner = inner;
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Update the region by processing all child modifications.
        /// <remarks>Note: The order of operations below is very important. Only by
        /// processing the related changes in this order will the update succeed.</remarks>
        /// </summary>
        /// <param name="region">The region to update.</param>
        public void UpdateRegion(Region region)
        {
            Region originalRegion = this.ChangeSet.GetOriginal(region);

            // Attach all unmodified entities
            foreach (Territory territory in this.ChangeSet.GetAssociatedChanges(region, p => p.Territories, ChangeOperation.None))
            {
                this.DbContext.Territories.Attach(territory);
            }
            if (originalRegion == null)
            {
                this.DbContext.Regions.Attach(region);
            }

            // Attach and apply changes to modified entities
            if (originalRegion != null)
            {
                this.DbContext.Regions.AttachAsModified(region, originalRegion, this.DbContext);
            }
            foreach (Territory territory in this.ChangeSet.GetAssociatedChanges(region, p => p.Territories, ChangeOperation.Update))
            {
                this.DbContext.Territories.AttachAsModified(territory, this.ChangeSet.GetOriginal(territory), this.DbContext);
            }

            // Add new entities
            foreach (Territory territory in this.ChangeSet.GetAssociatedChanges(region, p => p.Territories, ChangeOperation.Insert))
            {
                DbEntityEntry <Territory> entityEntry = this.DbContext.Entry(territory);
                if (entityEntry.State != EntityState.Detached)
                {
                    // need to change the object state if the entity was already eagerly added
                    entityEntry.State = EntityState.Added;
                }
                else
                {
                    this.DbContext.Territories.Add(territory);
                }
            }

            // Finally, process any deleted entites and relationships
            foreach (Territory territory in this.ChangeSet.GetAssociatedChanges(region, p => p.Territories, ChangeOperation.Delete))
            {
                Territory origTerrigory = this.ChangeSet.GetOriginal(territory);
                if (origTerrigory != null)
                {
                    this.DbContext.Territories.AttachAsModified(territory, origTerrigory, this.DbContext);
                }
                else
                {
                    this.DbContext.Territories.Attach(territory);
                }

                // need to remove any employee territory rows
                DbEntityEntry     tEntityEntry        = this.DbContext.Entry(territory);
                DbCollectionEntry employeesCollection = tEntityEntry.Collection("Employees");
                employeesCollection.Load();
                territory.Employees.Clear();

                this.DbContext.Territories.Remove(territory);
            }
        }
Ejemplo n.º 20
0
 public FilteredCollection(ICollection <TEntity> collection, DbCollectionEntry dbCollectionEntry)
 {
     _filter            = entity => !entity.Deleted;
     _dbCollectionEntry = dbCollectionEntry;
     _collection        = collection;
 }
Ejemplo n.º 21
0
        public virtual TEntity Find(params object[] keyValues)
        {
            TEntity entity;

            if (((IEnumerable <Type>) typeof(TEntity).GetInterfaces()).Any <Type>((Func <Type, bool>)(t => t.FullName == typeof(ICacheable).FullName)))
            {
                List <TEntity> source = CacheManager.GetData(typeof(TEntity).FullName) as List <TEntity>;
                if (source == null)
                {
                    source = this._dbSet.AsNoTracking().ToList <TEntity>();
                    CacheManager.Add(typeof(TEntity).FullName, (object)source);
                }
                entity = source.FirstOrDefault <TEntity>((Func <TEntity, bool>)(e => ((IEnumerable <object>)e.GetID()).Select <object, string>((Func <object, string>)(id => id.ToString())).SequenceEqual <string>(((IEnumerable <object>)keyValues).Select <object, string>((Func <object, string>)(id => id.ToString())))));
            }
            else
            {
                entity = this._dbSet.Find(keyValues);
            }
            if ((object)entity is IAggregateRoot || (object)entity is IAutoReferenceLoad)
            {
                DbContext context = this._context as DbContext;
                if (context == null)
                {
                    return(entity);
                }
                if (context.Entry <TEntity>(entity).State == EntityState.Detached)
                {
                    this._dbSet.Attach(entity);
                }
                foreach (PropertyInfo property in entity.GetType().GetProperties())
                {
                    if (!((IEnumerable <ParameterInfo>)property.GetIndexParameters()).Any <ParameterInfo>())
                    {
                        if ((object)entity is IAutoReferenceLoad && ((IEnumerable <Type>)property.PropertyType.GetInterfaces()).Any <Type>((Func <Type, bool>)(t => t.FullName == typeof(IObjectState).FullName)))
                        {
                            DbReferenceEntry dbReferenceEntry = context.Entry <TEntity>(entity).Reference(property.Name);
                            if (!dbReferenceEntry.IsLoaded)
                            {
                                dbReferenceEntry.Load();
                                if (dbReferenceEntry.CurrentValue is ILogicalDeletable && ((ILogicalDeletable)dbReferenceEntry.CurrentValue).IsDeleted)
                                {
                                    dbReferenceEntry.CurrentValue = (object)null;
                                }
                            }
                        }
                        else if ((object)entity is IAggregateRoot && ((IEnumerable <Type>)property.PropertyType.GetInterfaces()).Any <Type>((Func <Type, bool>)(t => t.Name == typeof(ICollection <>).Name)) && ((IEnumerable <Type>)property.PropertyType.GetGenericArguments()).Any <Type>((Func <Type, bool>)(type => ((IEnumerable <Type>)type.GetInterfaces()).Any <Type>((Func <Type, bool>)(t => t == typeof(IObjectState))))))
                        {
                            DbCollectionEntry dbCollectionEntry = context.Entry <TEntity>(entity).Collection(property.Name);
                            if (!dbCollectionEntry.IsLoaded)
                            {
                                if (((IEnumerable <Type>)property.PropertyType.GetGenericArguments()).Any <Type>((Func <Type, bool>)(type => ((IEnumerable <Type>)type.GetInterfaces()).Any <Type>((Func <Type, bool>)(t => t == typeof(ILogicalDeletable))))))
                                {
                                    IQueryable           queryable            = dbCollectionEntry.Query();
                                    Type                 genericArgument      = property.PropertyType.GetGenericArguments()[0];
                                    ParameterExpression  parameterExpression  = Expression.Parameter(genericArgument, "en");
                                    LambdaExpression     lambdaExpression     = Expression.Lambda((Expression)Expression.Equal((Expression)Expression.Property((Expression)parameterExpression, "IsDeleted"), (Expression)Expression.Constant((object)false, typeof(bool))), parameterExpression);
                                    MethodCallExpression methodCallExpression = Expression.Call(typeof(Queryable), "Where", new Type[1]
                                    {
                                        genericArgument
                                    }, queryable.Expression, (Expression)Expression.Quote((Expression)lambdaExpression));
                                    queryable.Provider.CreateQuery((Expression)methodCallExpression).Load();
                                }
                                else
                                {
                                    dbCollectionEntry.Load();
                                }
                            }
                        }
                    }
                }
            }
            return(entity);
        }
Ejemplo n.º 22
0
 public abstract object CreateCollection <TElement>(DbCollectionEntry collectionEntry);
Ejemplo n.º 23
0
        public override P AddToParent <P>(int parentId, T document)
        {
            //string sParentPropID = typeof(P).Name + "Key";
            //P parent = context.Database.SqlQuery<P>("select * from " + typeof(P).Name + " where " + sParentPropID + " = @p0", parentId).FirstOrDefault();

            DbSet <P> parentSet = context.Set <P>();
            P         parent    = parentSet.Find(parentId);

            if (parent == null)
            {
                throw new Exception("Non-existent Parent Entity.");
            }
            if (parent is BaseDocument)
            {
                if ((parent as BaseDocument).sys_active == false)
                {
                    throw new Exception("Non-existent Parent Entity.");
                }
            }

            //parentSet.Attach(parent);
            //context.Entry(parent).State = EntityState.Unchanged;


            string        navigationPropertyName = typeof(T).Name;
            DbMemberEntry memberEntry;

            try
            {
                memberEntry = context.Entry(parent).Member(navigationPropertyName);
            }
            catch (Exception)
            {
                try
                {
                    navigationPropertyName += "s";
                    memberEntry             = context.Entry(parent).Member(navigationPropertyName);
                }
                catch (Exception)
                {
                    throw new KnownError("Property not found: [" + navigationPropertyName + "]");
                }
            }

            if (memberEntry is DbCollectionEntry)
            {
                DbCollectionEntry <P, T> childrenCollection = context.Entry(parent).Collection <T>(navigationPropertyName);
                childrenCollection.Load();

                if (!childrenCollection.CurrentValue.Contains(document))
                {
                    childrenCollection.CurrentValue.Add(document);
                    if (document.id > 0)
                    {
                        context.Entry(document).State = EntityState.Unchanged;

                        document.InfoTrack = context.Set <Track>()
                                             .AsNoTracking()
                                             .FirstOrDefault(t => t.Entity_ID == document.id && t.Entity_Kind == document.AAA_EntityName);

                        if (document.InfoTrack != null)
                        {
                            document.InfoTrack.User_LastEditedByKey = ByUserId;
                            document.InfoTrack.Date_EditedOn        = DateTimeOffset.Now;

                            context.Entry(document.InfoTrack).State = EntityState.Modified;
                        }
                    }
                    else
                    {
                        context.Entry(document).State = EntityState.Added;

                        document.InfoTrack = new Track()
                        {
                            Date_CreatedOn     = DateTimeOffset.Now,
                            Entity_ID          = document.id,
                            Entity_Kind        = document.AAA_EntityName,
                            User_CreatedByKey  = ByUserId,
                            User_AssignedToKey = ByUserId
                        };
                        context.Entry(document.InfoTrack).State = EntityState.Added;
                    }

                    context.SaveChanges();
                }
            }
            else if (memberEntry is DbReferenceEntry)
            {
                DbReferenceEntry <P, T> childrenReference = context.Entry(parent).Reference <T>(navigationPropertyName);
                childrenReference.Load();

                if (childrenReference.CurrentValue == null || !childrenReference.CurrentValue.Equals(document))
                {
                    childrenReference.CurrentValue = document;
                    if (document.id > 0)
                    {
                        context.Entry(document).State = EntityState.Unchanged;

                        document.InfoTrack = context.Set <Track>()
                                             .AsNoTracking()
                                             .FirstOrDefault(t => t.Entity_ID == document.id && t.Entity_Kind == document.AAA_EntityName);

                        if (document.InfoTrack != null)
                        {
                            document.InfoTrack.User_LastEditedByKey = ByUserId;
                            document.InfoTrack.Date_EditedOn        = DateTimeOffset.Now;

                            context.Entry(document.InfoTrack).State = EntityState.Modified;
                        }
                    }
                    else
                    {
                        context.Entry(document).State = EntityState.Added;

                        document.InfoTrack = new Track()
                        {
                            Date_CreatedOn     = DateTimeOffset.Now,
                            Entity_ID          = document.id,
                            Entity_Kind        = document.AAA_EntityName,
                            User_CreatedByKey  = ByUserId,
                            User_AssignedToKey = ByUserId
                        };
                        context.Entry(document.InfoTrack).State = EntityState.Added;
                    }

                    context.SaveChanges();
                }
            }

            return(parent);
        }
Ejemplo n.º 24
0
        public P AddToParent <P>(int parentId, T entity) where P : class
        {
            //string sParentPropID = typeof(P).Name + "Key";
            //P parent = context.Database.SqlQuery<P>("select * from " + typeof(P).Name + " where " + sParentPropID + " = @p0", parentId).FirstOrDefault();

            DbSet <P> parentSet = context.Set <P>();
            P         parent    = parentSet.Find(parentId);

            if (parent == null)
            {
                throw new Exception("Non-existent Parent Entity.");
            }
            if (parent is BaseDocument)
            {
                if ((parent as BaseDocument).sys_active == false)
                {
                    throw new Exception("Non-existent Parent Entity.");
                }
            }

            //parentSet.Attach(parent);
            //context.Entry(parent).State = EntityState.Unchanged;


            string        navigationPropertyName = typeof(T).Name;
            DbMemberEntry memberEntry;

            try
            {
                memberEntry = context.Entry(parent).Member(navigationPropertyName);
            }
            catch (Exception)
            {
                try
                {
                    navigationPropertyName += "s";
                    memberEntry             = context.Entry(parent).Member(navigationPropertyName);
                }
                catch (Exception)
                {
                    throw new KnownError("Property not found: [" + navigationPropertyName + "]");
                }
            }

            if (memberEntry is DbCollectionEntry)
            {
                DbCollectionEntry <P, T> childrenCollection = context.Entry(parent).Collection <T>(navigationPropertyName);
                childrenCollection.Load();

                if (!childrenCollection.CurrentValue.Contains(entity))
                {
                    childrenCollection.CurrentValue.Add(entity);
                    if (entity.id > 0)
                    {
                        context.Entry(entity).State = EntityState.Unchanged;

                        /*DOCUMENT*/
                        if (typeof(T).IsSubclassOf(typeof(BaseDocument)))
                        {
                            var document = entity as BaseDocument;
                            document.InfoTrack = context.Set <Track>()
                                                 .AsNoTracking()
                                                 .FirstOrDefault(t => t.Entity_ID == document.id && t.Entity_Kind == document.AAA_EntityName);

                            if (document.InfoTrack != null)
                            {
                                document.InfoTrack.User_LastEditedByKey = byUserId;
                                document.InfoTrack.Date_EditedOn        = DateTime.Now;

                                context.Entry(document.InfoTrack).State = EntityState.Modified;
                            }
                        }
                    }
                    else
                    {
                        context.Entry(entity).State = EntityState.Added;

                        /*DOCUMENT*/
                        if (typeof(T).IsSubclassOf(typeof(BaseDocument)))
                        {
                            var document = entity as BaseDocument;
                            document.InfoTrack = new Track();
                            //(entity as Trackable).InfoTrack = trackRepository.GetSingle(context, t => t.Entity_ID == entity.ID && t.Entity_Kind == entity.AAA_EntityName);
                            document.InfoTrack.Date_CreatedOn     = DateTime.Now;
                            document.InfoTrack.Entity_ID          = document.id;
                            document.InfoTrack.Entity_Kind        = document.AAA_EntityName;
                            document.InfoTrack.User_CreatedByKey  = byUserId;
                            document.InfoTrack.User_AssignedToKey = byUserId;

                            context.Entry(document.InfoTrack).State = EntityState.Added;
                        }
                    }

                    context.SaveChanges();
                }
            }
            else if (memberEntry is DbReferenceEntry)
            {
                DbReferenceEntry <P, T> childrenReference = context.Entry(parent).Reference <T>(navigationPropertyName);
                childrenReference.Load();

                if (childrenReference.CurrentValue == null || !childrenReference.CurrentValue.Equals(entity))
                {
                    childrenReference.CurrentValue = entity;
                    if (entity.id > 0)
                    {
                        context.Entry(entity).State = EntityState.Unchanged;

                        /*DOCUMENT*/
                        if (typeof(T).IsSubclassOf(typeof(BaseDocument)))
                        {
                            var document = entity as BaseDocument;
                            document.InfoTrack = context.Set <Track>()
                                                 .AsNoTracking()
                                                 .FirstOrDefault(t => t.Entity_ID == document.id && t.Entity_Kind == document.AAA_EntityName);

                            if (document.InfoTrack != null)
                            {
                                document.InfoTrack.User_LastEditedByKey = byUserId;
                                document.InfoTrack.Date_EditedOn        = DateTime.Now;

                                context.Entry(document.InfoTrack).State = EntityState.Modified;
                            }
                        }
                    }
                    else
                    {
                        context.Entry(entity).State = EntityState.Added;

                        /*DOCUMENT*/
                        if (typeof(T).IsSubclassOf(typeof(BaseDocument)))
                        {
                            var document = entity as BaseDocument;
                            document.InfoTrack = new Track();
                            //(entity as Trackable).InfoTrack = trackRepository.GetSingle(context, t => t.Entity_ID == entity.ID && t.Entity_Kind == entity.AAA_EntityName);
                            document.InfoTrack.Date_CreatedOn     = DateTime.Now;
                            document.InfoTrack.Entity_ID          = document.id;
                            document.InfoTrack.Entity_Kind        = document.AAA_EntityName;
                            document.InfoTrack.User_CreatedByKey  = byUserId;
                            document.InfoTrack.User_AssignedToKey = byUserId;

                            context.Entry(document.InfoTrack).State = EntityState.Added;
                        }
                    }

                    context.SaveChanges();
                }
            }

            //DbSet<T> entitySet = context.Set<T>();
            //entitySet.Attach(entity);

            //PropertyInfo navigationProperty = parent.GetType().GetProperty(navigationPropertyName, BindingFlags.Public | BindingFlags.Instance);
            //ICollection<T> childrenList = (ICollection<T>)navigationProperty.GetValue(entity);

            //childrenList.Add(entity);

            return(parent);
        }
Ejemplo n.º 25
0
        public virtual P AddToParent <P>(int parentId, T entity) where P : class
        {
            //string sParentPropID = typeof(P).Name + "Key";
            //P parent = context.Database.SqlQuery<P>("select * from " + typeof(P).Name + " where " + sParentPropID + " = @p0", parentId).FirstOrDefault();

            DbSet <P> parentSet = context.Set <P>();
            P         parent    = parentSet.Find(parentId);

            if (parent == null)
            {
                throw new Exception("Non-existent Parent Entity.");
            }
            if (parent is BaseDocument)
            {
                if ((parent as BaseDocument).sys_active == false)
                {
                    throw new Exception("Non-existent Parent Entity.");
                }
            }

            //parentSet.Attach(parent);
            //context.Entry(parent).State = EntityState.Unchanged;


            string        navigationPropertyName = typeof(T).Name;
            DbMemberEntry memberEntry;

            try
            {
                memberEntry = context.Entry(parent).Member(navigationPropertyName);
            }
            catch (Exception)
            {
                try
                {
                    navigationPropertyName += "s";
                    memberEntry             = context.Entry(parent).Member(navigationPropertyName);
                }
                catch (Exception)
                {
                    throw new KnownError("Property not found: [" + navigationPropertyName + "]");
                }
            }

            if (memberEntry is DbCollectionEntry)
            {
                DbCollectionEntry <P, T> childrenCollection = context.Entry(parent).Collection <T>(navigationPropertyName);
                childrenCollection.Load();

                if (!childrenCollection.CurrentValue.Contains(entity))
                {
                    childrenCollection.CurrentValue.Add(entity);
                    if (entity.id > 0)
                    {
                        context.Entry(entity).State = EntityState.Unchanged;
                    }
                    else
                    {
                        context.Entry(entity).State = EntityState.Added;
                    }

                    context.SaveChanges();
                }
            }
            else if (memberEntry is DbReferenceEntry)
            {
                DbReferenceEntry <P, T> childrenReference = context.Entry(parent).Reference <T>(navigationPropertyName);
                childrenReference.Load();

                if (childrenReference.CurrentValue == null || !childrenReference.CurrentValue.Equals(entity))
                {
                    childrenReference.CurrentValue = entity;
                    if (entity.id > 0)
                    {
                        context.Entry(entity).State = EntityState.Unchanged;
                    }
                    else
                    {
                        context.Entry(entity).State = EntityState.Added;
                    }

                    context.SaveChanges();
                }
            }

            //DbSet<T> entitySet = context.Set<T>();
            //entitySet.Attach(entity);

            //PropertyInfo navigationProperty = parent.GetType().GetProperty(navigationPropertyName, BindingFlags.Public | BindingFlags.Instance);
            //ICollection<T> childrenList = (ICollection<T>)navigationProperty.GetValue(entity);

            //childrenList.Add(entity);

            return(parent);
        }
 public override object CreateCollection <TElement>(DbCollectionEntry collectionEntry)
 {
     return(new QueryableCollection <TElement>(
                (ICollection <TElement>)collectionEntry.CurrentValue,
                collectionEntry.Query().Cast <TElement>()));
 }