示例#1
0
        /// <summary>
        /// Attaches an entity to the ALinq.DataContext in either a modified or unmodified state.
        /// </summary>
        /// <param name="entity">The entity to be attached.</param>
        /// <param name="asModified">True to attach the entity as modified.</param>
        public void Attach(TEntity entity, bool asModified)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }
            CheckReadOnly();
            context.CheckNotInSubmitChanges();
            context.VerifyTrackingEnabled();
            MetaType inheritanceType = metaTable.RowType.GetInheritanceType(entity.GetType());

            if (!IsTrackableType(inheritanceType))
            {
                throw Error.TypeCouldNotBeTracked(inheritanceType.Type);
            }
            if (asModified && ((inheritanceType.VersionMember == null) && inheritanceType.HasUpdateCheck))
            {
                throw Error.CannotAttachAsModifiedWithoutOriginalState();
            }
            TrackedObject trackedObject = Context.Services.ChangeTracker.GetTrackedObject(entity);

            if ((trackedObject != null) && !trackedObject.IsWeaklyTracked)
            {
                throw Error.CannotAttachAlreadyExistingEntity();
            }
            if (trackedObject == null)
            {
                trackedObject = context.Services.ChangeTracker.Track(entity, true);
            }
            if (asModified)
            {
                trackedObject.ConvertToModified();
            }
            else
            {
                trackedObject.ConvertToUnmodified();
            }
            if (Context.Services.InsertLookupCachedObject(inheritanceType, entity) != entity)
            {
                throw new DuplicateKeyException(entity, Strings.CantAddAlreadyExistingKey);
            }
            trackedObject.InitializeDeferredLoaders();

            //TODO:SetDataContext
            if (metaTable.RowType.HasAnySetDataContextMethod)
            {
                context.Services.SendSetDataContext(inheritanceType, entity, new object[] { this.context });
            }
        }