コード例 #1
0
        public async Task <IEnumerable <T> > GetAsync <T>(IEnumerable <int> ids) where T : class
        {
            // Auto-flush
            await CommitAsync(keepTracked : true);

            var result = new List <T>();

            if (ids == null || !ids.Any())
            {
                return(result);
            }

            // Are all the objects already in cache?
            IEnumerable <object> cached = ids.Select(id =>
            {
                object entity;
                if (_identityMap.TryGetEntityById(id, out entity))
                {
                    return(entity);
                }
                return(null);
            });

            if (!cached.Any(x => x == null))
            {
                foreach (T item in cached)
                {
                    result.Add(item);
                }
            }

            // Some documents might not be in cache, load all of them from storage, then resolve local maps
            var items = (await _storage.GetAsync <T>(ids.ToArray())).ToArray();

            // if the document has an Id property, set it back
            var accessor = _store.GetIdAccessor(typeof(T), "Id");

            for (int i = 0; i < items.Length; i++)
            {
                var item = items[i];
                var id   = ids.ElementAt(i);

                object entity;

                if (_identityMap.TryGetEntityById(id, out entity))
                {
                    result.Add((T)entity);
                }
                else
                {
                    if (accessor != null)
                    {
                        accessor.Set(item, id);
                    }

                    // track the loaded object
                    _identityMap.Add(id, item);

                    result.Add(item);
                }
            }

            return(result);
        }