예제 #1
0
        public IQueryable <TRelation> LoadQuery <TRelation>(Expression <Func <TEntity, TRelation> > accessor)
            where TRelation : class
        {
            DbEntityEntry <TEntity> entry = context.Entry(entity);
            DbReferenceEntry <TEntity, TRelation> reference = entry.Reference(accessor);

            return(reference.Query());
        }
예제 #2
0
        public virtual void LoadReference <TProperty>(TEntity entity, Expression <Func <TEntity, TProperty> > member, bool forceReload = false) where TProperty : class
        {
            DbReferenceEntry <TEntity, TProperty> reference = _dbContext.Entry(entity).Reference(member);

            if (forceReload == true || reference.IsLoaded == false)
            {
                reference.Load();
            }
        }
예제 #3
0
        public virtual async Task LoadReferenceAsync <TProperty>(TEntity entity, Expression <Func <TEntity, TProperty> > member, CancellationToken cancellationToken, bool forceReload = false) where TProperty : class
        {
            DbReferenceEntry <TEntity, TProperty> reference = _dbContext.Entry(entity).Reference(member);

            if (forceReload == true || reference.IsLoaded == false)
            {
                await reference.LoadAsync(cancellationToken).ConfigureAwait(false);
            }
        }
예제 #4
0
        public void Load <TRelation>(Expression <Func <TEntity, TRelation> > accessor)
            where TRelation : class
        {
            DbEntityEntry <TEntity> entry     = context.Entry(entity);
            DbReferenceEntry        reference = entry.Reference(accessor);

            if (!reference.IsLoaded)
            {
                reference.Load();
            }
        }
예제 #5
0
        public virtual void LoadReference <TProperty>(TEntity entity, Expression <Func <TEntity, TProperty> > member)
            where TProperty : class
        {
            Attach(entity);

            DbReferenceEntry <TEntity, TProperty> reference = _dbContext.Entry(entity).Reference(member);

            if (reference.IsLoaded == false)
            {
                reference.Load();
            }
        }
예제 #6
0
파일: UT2.cs 프로젝트: uwitec/mb-oa
        //[TestMethod]
        public void TestAttach()
        {
            LinkMethod lm = null;

            using (MyDBExt db = new MyDBExt())
            {
                lm = db.LinkMethods.Include(p => p.user).FirstOrDefault();
            }

            User user = null;

            using (MyDBExt db = new MyDBExt())
            {
                user = db.Users.FirstOrDefault(u => !u.Code.Equals(lm.user.ID));
            }

            lm.MethodType = "B";
            lm.user       = user;

            using (MyDBExt db = new MyDBExt())
            {
                // 附加到新上下文
                // 方法一
                //db.Entry(lm).State = System.Data.EntityState.Modified;
                //db.Entry<User>(lm.user).State = System.Data.EntityState.Modified;
                db.LinkMethods.Add(lm); // lm.user的状态也是Added,如果不把lm.user的状态设置为Unchanged,就会出现主键重复的错误
                db.Entry <LinkMethod>(lm).State = System.Data.EntityState.Modified;
                //db.Entry<User>(lm.user).State = System.Data.EntityState.Unchanged;

                DbReferenceEntry dre = db.Entry <LinkMethod>(lm).Reference(l => l.user);
                bool             x   = dre.IsLoaded;
                User             u   = lm.user;
                x = dre.IsLoaded;
                DbEntityEntry <LinkMethod> dee = db.Entry <LinkMethod>(lm);
                DbPropertyEntry            dpe = dee.Property(l => l.MethodType);


                //db.LinkMethods.Attach(lm);


                //lm.user = user;

                db.SaveChanges();
            }

            using (MyDBExt db = new MyDBExt())
            {
                IQueryable s = db.Users.Select(u => new { u, xX = db.LinkMethods.Where(l => l.user.ID.Equals(u.ID)).Count() });  // OK
                //IQueryable s = db.Users.Select(u => new { u, xX = db.LinkMethods.Where(l => l.user.ID.Equals(u.ID)).Select(l => l.MethodType) });  //NO
                //IQueryable s = db.Users.Select(u => new { u, xX = "ddddddddddddd" }); //OK
            }
        }
예제 #7
0
        public void Load <TRelation>(Expression <Func <TEntity, TRelation> > accessor)
            where TRelation : class
        {
            Func <TEntity, bool> isLoaded = e =>
            {
                DbEntityEntry <TEntity> entry = context.Entry(e);
                DbReferenceEntry <TEntity, TRelation> reference = entry.Reference(accessor);
                return(reference.IsLoaded);
            };
            Expression <Func <TEntity, bool> > expression = getFilterExpression(isLoaded);

            if (expression == null)
            {
                return;
            }
            context.Set <TEntity>().Where(expression).Join(context.Set <TRelation>(), accessor, r => r, (e, r) => r).Load();
        }
        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);
        }
예제 #9
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);
        }
예제 #10
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);
        }
예제 #11
0
 public WrapperDbReferenceEntry(DbReferenceEntry <TEntity, TProperty> inner)
 {
     this.inner = inner;
 }
예제 #12
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);
        }