示例#1
0
        private static void DoLoadCollection <T, TProperty>(DbContext context, EntityEntry <T> entry, FilteredIncludeExpression filteredInclude) where T : class where TProperty : class
        {
            List <TProperty> collection = filteredInclude.Filter != null
                ? entry.Collection((Expression <Func <T, IEnumerable <TProperty> > >) filteredInclude.Include)
                                          .Query()
                                          .Where((Expression <Func <TProperty, bool> >)filteredInclude.Filter).ToList()
                : entry.Collection((Expression <Func <T, IEnumerable <TProperty> > >)filteredInclude.Include)
                                          .Query()
                                          .ToList();

            if (filteredInclude.FilteredIncludes == null || filteredInclude.FilteredIncludes.Count == 0)
            {
                return;
            }

            filteredInclude.FilteredIncludes.ToList().ForEach(exp =>
            {
                context.InvokeMethodForCollection
                (
                    collection,
                    exp.Include.Body.GetMemberExpression().GetMemberType(),
                    exp
                );
            });
        }
        public async Task LoadDetailsAsync(PlaylistDefinition playlistDefinition)
        {
            EntityEntry <PlaylistDefinition> entry = DataContext.Entry(playlistDefinition);

            await entry.Reference(o => o.User).LoadAsync();

            await entry.Collection(o => o.PlaylistSources).LoadAsync();

            await entry.Collection(o => o.OrderInstructions).LoadAsync();
        }
示例#3
0
        private void LoadRelations(PropertyPath <TEntity> path)
        {
            EntityEntry node = entity;

            foreach (var prop in path.Properties)
            {
                var isCollection = typeof(IEnumerable).IsAssignableFrom(prop.PropertyType);

                if (isCollection && !ReferenceEquals(prop, path.Properties.Last()))
                {
                    throw new ArgumentException("Invalid path: " + path);
                }

                if (isCollection)
                {
                    node.Collection(prop.Name).Load();
                }
                else
                {
                    var refEntity = node.Reference(prop.Name);
                    refEntity.Load();

                    if (refEntity.CurrentValue == null)
                    {
                        return;
                    }

                    node = entity.Context.Entry(refEntity.CurrentValue);
                }
            }
        }
示例#4
0
        public IQueryable <TCollection> QueryRelation <TCollection>(Expression <Func <TEntity, ICollection <TCollection> > > expr)
        {
            var path = PropertyPath <TEntity> .Create(expr);

            EntityEntry node = entity;

            foreach (var prop in path.Properties.Take(path.Properties.Count - 1))
            {
                var isCollection = typeof(IEnumerable).IsAssignableFrom(prop.PropertyType);

                if (isCollection && !ReferenceEquals(prop, path.Properties.Last()))
                {
                    throw new ArgumentException("Invalid path: " + expr);
                }

                var refEntity = node.Reference(prop.Name);
                refEntity.Load();

                if (refEntity.CurrentValue == null)
                {
                    throw new NullReferenceException();
                }

                node = entity.Context.Entry(refEntity.CurrentValue);
            }

            return((IQueryable <TCollection>)node.Collection(path.Properties.Last().Name).Query());
        }
        public void GetBooksWithExplicitLoading()
        {
            var books = _booksContext.Books.TagWith("Explicit").Where(b => b.Publisher.StartsWith("Wrox"));

            foreach (var book in books)
            {
                Console.WriteLine(book.Title);
                EntityEntry <Book> entry = _booksContext.Entry(book);
                entry.Collection(b => b.Chapters).Load();

                foreach (var chapter in book.Chapters)
                {
                    Console.WriteLine($"{chapter.Number}. {chapter.Title}");
                }

                entry.Reference(b => b.Author).Load();
                Console.WriteLine($"author: {book.Author?.Name}");

                entry.Reference(b => b.Reviewer).Load();
                Console.WriteLine($"reviewer: {book.Reviewer?.Name}");

                entry.Reference(b => b.Editor).Load();
                Console.WriteLine($"editor: {book.Editor?.Name}");
            }
        }
        private static void MarkDeletedItemsRecursively(
            EntityEntry entryBeforeUpdate,
            EntityEntry entryToUpdate,
            DbContext dbContext)
        {
            foreach (var collectionsForEntryToUpdate in entryToUpdate.Collections)
            {
                var collectionBeforeUpdate = entryBeforeUpdate.Collection(collectionsForEntryToUpdate.Metadata.Name).CurrentValue.Cast <object>().ToList();
                var collectionToUpdate     = collectionsForEntryToUpdate.CurrentValue.Cast <object>().ToList();

                foreach (var collectionEntityBeforeUpdate in collectionBeforeUpdate)
                {
                    var collectionEntryBeforeUpdate = dbContext.Entry(collectionEntityBeforeUpdate);
                    var currentEntityToUpdate       = collectionToUpdate.FirstOrDefault(f => f.Equals(collectionEntityBeforeUpdate));

                    if (currentEntityToUpdate == null)
                    {
                        collectionEntryBeforeUpdate.State = EntityState.Deleted;
                    }
                    else
                    {
                        var currentEntityEntryAfterUpdate = dbContext.Entry(currentEntityToUpdate);
                        MarkDeletedItemsRecursively(collectionEntryBeforeUpdate, currentEntityEntryAfterUpdate, dbContext);
                    }
                }
            }
        }
示例#7
0
        /// <summary>
        /// Az étterem modell osztály átalakítása részletes adatokat tartalmazó adatátviteli objektummá.
        /// </summary>
        /// <param name="restaurant">Étterem típusú entitás.</param>
        /// <returns>Az étterem részletes adatait tartalmazó adatátviteli objektum.</returns>
        public static async Task <RestaurantDetailsDto> ToRestaurantDetailsDto(this EntityEntry <Restaurant> restaurant)
        {
            await restaurant.Collection(r => r.Reviews).LoadAsync();

            await restaurant.Reference(r => r.Owner).LoadAsync();

            return(new RestaurantDetailsDto(restaurant.Entity));
        }
        /// <summary>
        /// A rendelés modell osztály átalakítása részletes adatokat tartalmazó adatátviteli objektummá.
        /// </summary>
        /// <param name="order">Rendelés típusú entitás.</param>
        /// <returns>A rendelés részletes adatait tartalmazó adatátviteli objektum.</returns>
        public static async Task <OrderDetailsDto> ToOrderDetailsDto(this EntityEntry <Order> order)
        {
            await order.Reference(o => o.Invoice).LoadAsync();

            await order.Collection(o => o.OrderFoods).Query()
            .Include(of => of.Food).LoadAsync();

            return(new OrderDetailsDto(order.Entity));
        }
示例#9
0
        public static void LoadCollection <TEntity, TRelationEntity>(
            this DbContext context,
            TEntity entity,
            Expression <Func <TEntity, IEnumerable <TRelationEntity> > > getTmmExpression
            ) where TEntity : class where TRelationEntity : class
        {
            EntityEntry <TEntity> entry = context.Entry(entity);
            var col = entry.Collection(getTmmExpression);

            col.Load();
        }
示例#10
0
        public async Task <IActionResult> GetUser()
        {
            string id   = User.FindFirst("id").Value;
            User   user = await UserManager.FindByIdAsync(id);

            if (user == null)
            {
                return(Unauthorized());
            }

            if (!user.PhoneNumberConfirmed)
            {
                return(new OkObjectResult(Mapper.Map <UserLoginViewModel>(user)));
            }

            EntityEntry <User> entry = UserDataContext.Entry(user);

            await entry.Collection(u => u.Photos).LoadAsync();

            await entry.Collection(u => u.Activities).LoadAsync();

            return(new OkObjectResult(Mapper.Map <UserProfileViewModel>(user)));
        }
示例#11
0
        public IEntry <TEntity> LoadRelations <TCollection, TProperty>(
            Expression <Func <TEntity, ICollection <TCollection> > > collectionExpr,
            Expression <Func <TCollection, TProperty> > propExpr = null
            )
            where TProperty : class
            where TCollection : class
        {
            var path = PropertyPath <TEntity> .Create(collectionExpr);

            EntityEntry node = entity;

            foreach (var prop in path.Properties.Take(path.Properties.Count - 1))
            {
                if (typeof(IEnumerable).IsAssignableFrom(prop.PropertyType))
                {
                    throw new ArgumentException("Invalid path: " + collectionExpr);
                }

                var refEntity = node.Reference(prop.Name);
                refEntity.Load();

                if (refEntity.CurrentValue == null)
                {
                    return(this);
                }

                node = entity.Context.Entry(refEntity.CurrentValue);
            }

            node.Collection(path.Properties.Last().Name).Load();

            if (propExpr != null)
            {
                var collection = (ICollection <TCollection>)path.Properties.Last().GetValue(node.Entity);

                foreach (var item in collection)
                {
                    var entry = new Entry <TCollection>(entity.Context.Entry(item));
                    entry.LoadRelations(propExpr);
                }
            }

            return(this);
        }
示例#12
0
        public async Task PostPersistAction(EntityEntry entry, ISet <EntityMutationInfo> cache)
        {
            var actionResult = new ActionResult();

            if (!(IsReference || cache.Contains(this)))
            {
                cache.Add(this);
                if (RuleMap != null)
                {
                    switch (State)
                    {
                    case (EntityState.Added): { await RuleMap.OnAfterCreation(MutationContext.SecurityContext, Entity, entry, this); break; }

                    case (EntityState.Modified): { await RuleMap.OnAfterEdition(MutationContext.SecurityContext, Entity, entry); break; }

                    case (EntityState.Deleted): { await RuleMap.OnAfterDeletion(MutationContext.SecurityContext, Entity, entry); break; }
                    }
                }
                foreach (var reference in References.Values.Where(reference => reference.TargetEntityMutationInfo != null))
                {
                    var targetEntry = entry.Reference(reference.Navigation.Name).TargetEntry;
                    if (targetEntry != null)
                    {
                        await reference.TargetEntityMutationInfo.PostPersistAction(targetEntry, cache);
                    }
                }
                foreach (var collectionMutationInfo in Collections.Values)
                {
                    var index      = 0;
                    var collection = (IEnumerable <object>)collectionMutationInfo.Navigation.GetGetter().GetClrValue(Entity);
                    foreach (var targetEntityMutationInfo in collectionMutationInfo.TargetEntityMutationInfos)
                    {
                        if (targetEntityMutationInfo.State != EntityState.Deleted)
                        {
                            await targetEntityMutationInfo.PostPersistAction(entry.Collection(collectionMutationInfo.Navigation.Name).FindEntry(collection.ElementAt(index)), cache);

                            index++;
                        }
                    }
                }
            }
        }
示例#13
0
        public async Task PrepareEntry(EntityEntry entry, ISet <EntityMutationInfo> cache)
        {
            if (!(IsReference || cache.Contains(this)))
            {
                cache.Add(this);
                var isGeneratedPrimaryKey = PrimaryKey.Properties[0].ValueGenerated.HasFlag(ValueGenerated.OnAdd);
                var unwantedProperties    = Properties.Values.Where(property => {
                    return((property.Property.ValueGenerated.HasFlag(ValueGenerated.OnAdd) && property.Property.IsPrimaryKey()) ||
                           (State != EntityState.Added && property.Property.IsPrimaryKey()));
                }).ToArray();
                var touchedProperties = Properties.Values.Where(p => !unwantedProperties.Any(up => up == p) && p.IsTouched).ToArray();
                if (State == EntityState.Deleted || State == EntityState.Added)
                {
                    entry.State = State;
                }
                foreach (var property in touchedProperties.Where(p => !p.Property.IsPrimaryKey()))
                {
                    entry.Property(property.Property.Name).IsModified = property.IsModified;
                }
                foreach (var referenceMutationInfo in References.Values.Where(r => r.IsModified))
                {
                    var reference = entry.Reference(referenceMutationInfo.Navigation.Name);
                    reference.IsModified = referenceMutationInfo.IsModified;
                    if (reference.TargetEntry != null)
                    {
                        await referenceMutationInfo.TargetEntityMutationInfo.PrepareEntry(reference.TargetEntry, cache);
                    }
                }
                foreach (var collectionMutationInfo in Collections.Values.Where(c => c.IsModified))
                {
                    var collection = entry.Collection(collectionMutationInfo.Navigation.Name);
                    collection.IsModified = collectionMutationInfo.IsModified;
                    var index = 0;
                    foreach (var item in collectionMutationInfo.TargetEntityMutationInfos)
                    {
                        await item.PrepareEntry(collection.FindEntry(collection.CurrentValue.Cast <object>().ElementAt(index)), cache);

                        index++;
                    }
                }
            }
        }
示例#14
0
        private NavigationEntry GetNavigationEntry(TResource resource, RelationshipAttribute relationship)
        {
            EntityEntry<TResource> entityEntry = _dbContext.Entry(resource);

            switch (relationship)
            {
                case HasOneAttribute hasOneRelationship:
                {
                    return entityEntry.Reference(hasOneRelationship.Property.Name);
                }
                case HasManyAttribute hasManyRelationship:
                {
                    return entityEntry.Collection(hasManyRelationship.Property.Name);
                }
                default:
                {
                    throw new InvalidOperationException($"Unknown relationship type '{relationship.GetType().Name}'.");
                }
            }
        }
示例#15
0
        private void TreatList(T entity, T dbEntity, EntityEntry <T> dbEntry, Expression <Func <T, object> > property)
        {
            var propertyName = property.GetPropertyAccess().Name;
            var dbItemsEntry = dbEntry.Collection(propertyName);
            var accessor     = dbItemsEntry.Metadata.GetCollectionAccessor();

            dbItemsEntry.Load();
            var dbItemsMap = ((IEnumerable <BaseEntity>)dbItemsEntry.CurrentValue)
                             .ToDictionary(e => e.Id);

            var items = (IEnumerable <BaseEntity>)accessor.GetOrCreate(entity, false);

            foreach (var item in items)
            {
                EntityEntry entityEntryChild = null;
                if (!dbItemsMap.TryGetValue(item.Id, out var oldItem))
                {
                    accessor.Add(dbEntity, item, false);
                    Db.Entry(item).State = EntityState.Added;
                    entityEntryChild     = Db.Entry(item);
                }
                else
                {
                    Db.Entry(oldItem).CurrentValues.SetValues(item);
                    Db.Entry(oldItem).State = EntityState.Modified;

                    entityEntryChild = Db.Entry(oldItem);

                    dbItemsMap.Remove(item.Id);
                }
            }

            foreach (var oldItem in dbItemsMap.Values)
            {
                accessor.Remove(dbEntity, oldItem);
            }
        }
示例#16
0
 public FindBuilder <TEntity> IncludeCollection <TProperty>(Expression <Func <TEntity, IEnumerable <TProperty> > > propertyExpression)
     where TProperty : class
 {
     _entry.Collection(propertyExpression).Load();
     return(this);
 }