Exemplo n.º 1
0
 /// <summary>
 /// Gets the column members.
 /// </summary>
 /// <param name="entityType">Type of the entity.</param>
 /// <param name="metaModel">The meta model.</param>
 /// <returns></returns>
 protected virtual IEnumerable<MemberInfo> GetColumnMembers(Type entityType, MetaModel metaModel)
 {
     foreach (var dataMember in metaModel.GetTable(entityType).RowType.PersistentDataMembers)
     {
         yield return dataMember.Member;
     }
 }
Exemplo n.º 2
0
    public void SetUp ()
    {
      _readerMock = MockRepository.GenerateMock<IDataReader>();
      _reverseMappingResolverMock = MockRepository.GenerateMock<IReverseMappingResolver>();

      _metaModel = new AttributeMappingSource().GetModel (typeof (DataContextTestClass));
    }
Exemplo n.º 3
0
 /// <summary>
 /// Adds simple (value) properties of an object to a given dictionary
 /// and recurses if a property contains complex data
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="rawData"></param>
 /// <param name="prefix"></param>
 /// <param name="metaModel"></param>
 protected void AddRawData(object entity, IDictionary<string, object> rawData, string prefix, MetaModel metaModel)
 {
     if (entity == null)
         return;
     foreach (var memberInfo in GetColumnMembers(entity.GetType(), metaModel))
     {
         var propertyValue = memberInfo.GetMemberValue(entity);
         // if it is a value, it can be stored directly
         var memberType = memberInfo.GetMemberType();
         if (IsPrimitiveType(memberType))
         {
             rawData[prefix + memberInfo.Name] = propertyValue;
         }
         else if (memberType.NotQuerableEnumerable())
         {
             if (propertyValue != null)
             {
                 var arrayValue = (Array) propertyValue;
                 for (int arrayIndex = 0; arrayIndex < arrayValue.Length; arrayIndex++)
                 {
                     rawData[string.Format("{0}[{1}]", memberInfo.Name, arrayIndex)] =
                         arrayValue.GetValue(arrayIndex);
                 }
             }
         }
         else // otherwise, we recurse, and prefix the current property name to sub properties to avoid conflicts
         {
             AddRawData(propertyValue, rawData, memberInfo.Name + ".", metaModel);
         }
     }
 }
Exemplo n.º 4
0
 public RepositoryMetaType(string workspace, MetaType original, MetaTable table, MetaModel metaModel)
 {
     this.Workspace = workspace;
     this.Original = original;
     this.RepositoryMetaTable = table;
     this.RepositoryMetaModel = metaModel;
 }
Exemplo n.º 5
0
 public RepositoryMetaTable(string workspace, MetaTable orig, MetaModel model)
 {
     this.Workspace = workspace;
     this.Original = orig;
     this.RepositoryMetaModel = model;
     this.RepositoryMetaType = new RepositoryMetaType(workspace, orig.RowType, this, model);
 }
Exemplo n.º 6
0
 public DatabaseMappedSamples(string connectionString, MetaModel mapping, TextWriter log)
 {
     this.db = new NorthwindDatabase(connectionString, mapping) {
     Configuration = {
        Log = log
     }
      };
 }
Exemplo n.º 7
0
        public CustomMetaTable(MetaTable table, MetaModel model)
        {
            _table = table;
            _model = model;

            _tableName = (_table.TableName.Contains(".") ? "" : "dbo.") + _table.TableName;

            var tableNameField = table.GetType().GetField("tableName", BindingFlags.NonPublic | BindingFlags.Instance);
            tableNameField.SetValue(_table, _tableName);
        }
Exemplo n.º 8
0
		private object locktarget = new object(); // Hold locks on private object rather than public MetaType.
		#endregion

		internal MappedType(MetaModel model, MetaTable table, TypeMapping typeMapping, Type type, MetaType inheritanceRoot)
		{
			this.model = model;
			this.table = table;
			this.typeMapping = typeMapping;
			this.type = type;
			this.inheritanceRoot = inheritanceRoot != null ? inheritanceRoot : this;
			this.InitDataMembers();

			this.identities = this.dataMembers.Where(m => m.IsPrimaryKey).ToList().AsReadOnly();
			this.persistentDataMembers = this.dataMembers.Where(m => m.IsPersistent).ToList().AsReadOnly();
		}
Exemplo n.º 9
0
		object locktarget = new object(); // Hold locks on private object rather than public MetaType.

		internal AttributedMetaType(MetaModel model, MetaTable table, Type type, MetaType inheritanceRoot)
		{
			this.model = model;
			this.table = table;
			this.type = type;
			this.inheritanceRoot = (inheritanceRoot != null) ? inheritanceRoot : this;
			// Not lazy-loading to simplify locking and enhance performance 
			// (because no lock will be required for the common read scenario).
			this.InitDataMembers();
			this.identities = this.dataMembers.Where(m => m.IsPrimaryKey).ToList().AsReadOnly();
			this.persistentMembers = this.dataMembers.Where(m => m.IsPersistent).ToList().AsReadOnly();
		}
Exemplo n.º 10
0
		internal MemberAccessBinder(SqlBinder binder, Translator translator, SqlColumnizer columnizer, NodeFactory sqlFactory, MetaModel model, DataLoadOptions shape, bool canUseOuterApply) {
			this.binder = binder;
			this.translator = translator;
			this.columnizer = columnizer;
			this.sql = sqlFactory;
			this.typeProvider = sqlFactory.TypeProvider;
			this.expander = new SqlExpander(this.sql);
			this.aggregateChecker = new SqlAggregateChecker();
			this.linkMap = new LinkOptimizationScope(null);
			this.outerAliasMap = new Dictionary<SqlAlias, SqlAlias>();
			this.model = model;
			this.shape = shape;
			this.canUseOuterApply = canUseOuterApply;
		}
        public AttributedMetaTable(TableAttribute attribute, MetaType type, MetaModel model)
        {
            _tableAttribute = attribute;
            _metaType = type;
        	_containingModel = model;

			//If the attribute doesn't specify a table name the name of the table class is used
			if(!string.IsNullOrEmpty(attribute.Name))
			{
				_tableName = attribute.Name;
			}
			else
			{
				_tableName = type.Name;
			}
        }
Exemplo n.º 12
0
		public DLinqDataModelProvider (Func<object> factory)
		{
			this.factory = factory;
			Type type = CreateContext ().GetType ();

			if (!typeof (DataContext).IsAssignableFrom (type))
				throw new ArgumentException (String.Format ("Type '{0}' is not supported as data context factory", type));

			this.factory = factory;

			model = new AttributeMappingSource ().GetModel (type);
			ContextType = model.ContextType;

			var l = new List<TableProvider> ();
			foreach (var m in model.GetTables ())
				l.Add (new DLinqTableProvider (this, m));
			tables = new ReadOnlyCollection<TableProvider> (l);
		}
 /// <summary>
 /// Adds simple (value) properties of an object to a given dictionary
 /// and recurses if a property contains complex data
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="rawData"></param>
 /// <param name="prefix"></param>
 /// <param name="metaModel"></param>
 protected void AddRawData(object entity, IDictionary<string, object> rawData, string prefix, MetaModel metaModel)
 {
     if (entity == null)
         return;
     foreach (var memberInfo in GetColumnMembers(entity.GetType(), metaModel))
     {
         object propertyValue = memberInfo.GetMemberValue(entity);
         // if it is a value, it can be stored directly
         if (IsPrimitiveType(memberInfo.GetMemberType()))
         {
             rawData[prefix + memberInfo.Name] = propertyValue;
         }
         else // otherwise, we recurse, and prefix the current property name to sub properties to avoid conflicts
         {
             AddRawData(propertyValue, rawData, memberInfo.Name + ".", metaModel);
         }
     }
 }
Exemplo n.º 14
0
        public DLinqDataModelProvider(Func <object> factory)
        {
            this.factory = factory;
            Type type = CreateContext().GetType();

            if (!typeof(DataContext).IsAssignableFrom(type))
            {
                throw new ArgumentException(String.Format("Type '{0}' is not supported as data context factory", type));
            }

            this.factory = factory;

            model       = new AttributeMappingSource().GetModel(type);
            ContextType = model.ContextType;

            var l = new List <TableProvider> ();

            foreach (var m in model.GetTables())
            {
                l.Add(new DLinqTableProvider(this, m));
            }
            tables = new ReadOnlyCollection <TableProvider> (l);
        }
        /// <summary>
        /// Constructor that creates a metadata context for the specified LINQ To SQL domain service type
        /// </summary>
        /// <param name="dataContextType">The DataContext type</param>
        public LinqToSqlTypeDescriptionContext(Type dataContextType)
        {
            if (dataContextType == null)
            {
                throw new ArgumentNullException("dataContextType");
            }

            System.Data.Linq.DataContext dataContext = null;
            try
            {
                dataContext = (System.Data.Linq.DataContext)Activator.CreateInstance(dataContextType, String.Empty);
            }
            catch (TargetInvocationException tie)
            {
                if (tie.InnerException != null)
                {
                    throw tie.InnerException;
                }
                
                throw;
            }
            this._model = dataContext.Mapping;
        }
Exemplo n.º 16
0
		[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
		internal MappedFunction(MappedMetaModel model, FunctionMapping map, MethodInfo method)
		{
			this.model = model;
			this.map = map;
			this.method = method;
			this.rowTypes = _emptyTypes;

			if(map.Types.Count == 0 && this.method.ReturnType == typeof(IMultipleResults))
			{
				throw Error.NoResultTypesDeclaredForFunction(method.Name);
			}
			else if(map.Types.Count > 1 && this.method.ReturnType != typeof(IMultipleResults))
			{
				throw Error.TooManyResultTypesDeclaredForFunction(method.Name);
			}
			else if(map.Types.Count == 1 && this.method.ReturnType != typeof(IMultipleResults))
			{
				Type elementType = TypeSystem.GetElementType(method.ReturnType);
				this.rowTypes = new List<MetaType>(1) { this.GetMetaType(map.Types[0], elementType) }.AsReadOnly();
			}
			else if(map.Types.Count > 0)
			{
				List<MetaType> rowTypes = new List<MetaType>();
				foreach(TypeMapping rtm in map.Types)
				{
					Type elementType = model.FindType(rtm.Name);
					if(elementType == null)
					{
						throw Error.CouldNotFindElementTypeInModel(rtm.Name);
					}
					MetaType mt = this.GetMetaType(rtm, elementType);
					// Only add unique meta types
					if(!rowTypes.Contains(mt))
					{
						rowTypes.Add(mt);
					}
				}
				this.rowTypes = rowTypes.AsReadOnly();
			}
			else if(map.FunReturn != null)
			{
				this.returnParameter = new MappedReturnParameter(method.ReturnParameter, map.FunReturn);
			}

			// Parameters.
			ParameterInfo[] pis = this.method.GetParameters();
			if(pis.Length > 0)
			{
				List<MetaParameter> mps = new List<MetaParameter>(pis.Length);
				if(this.map.Parameters.Count != pis.Length)
				{
					throw Error.IncorrectNumberOfParametersMappedForMethod(this.map.MethodName);
				}
				for(int i = 0; i < pis.Length; i++)
				{
					mps.Add(new MappedParameter(pis[i], this.map.Parameters[i]));
				}
				this.parameters = mps.AsReadOnly();
			}
			else
			{
				this.parameters = _emptyParameters;
			}
		}
Exemplo n.º 17
0
        /// <summary>
        /// Gets modified properties for entity, by using raw compare method.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="metaModel">The meta model.</param>
        /// <returns></returns>
        protected IList<MemberInfo> GetRawModifiedProperties(object entity, MetaModel metaModel)
        {
            var properties = new List<MemberInfo>();

            IDictionary<string, object> originalData;
            // if we don't have this entity we consider all its properties as having been modified
            if (!rawDataEntities.TryGetValue(entity, out originalData))
                return GetAllColumnProperties(entity, metaModel);
            var currentData = GetEntityRawData(entity, metaModel);

            // otherwise, we iterate and find what's changed
            foreach (string key in currentData.Keys)
            {
                var currentValue = currentData[key];
                var originalValue = originalData[key];
                if (IsPropertyModified(originalValue, currentValue))
                    properties.Add(GetProperty(entity, key));
            }

            return properties;
        }
Exemplo n.º 18
0
 /// <summary>
 /// Get a MetaType that represents the dynamic type of the given node.
 /// </summary>
 internal static MetaType GetSourceMetaType(SqlNode node, MetaModel model) {
     Visitor v = new Visitor();
     v.Visit(node);
     Type type = v.sourceType;
     type = TypeSystem.GetNonNullableType(type); // Emulate CLR's behavior: strip nullability from type.
     return model.GetMetaType(type);
 }
Exemplo n.º 19
0
        /// <summary>
        /// Gets the MetaModel representing a DataContext and all it's
        /// accessible tables, functions and entities.
        /// </summary>
        public MetaModel GetModel(Type dataContextType)
        {
            if (dataContextType == null)
            {
                throw Error.ArgumentNull("dataContextType");
            }

            MetaModel model = null;

            if (primaryModel == null)
            {
                model = CreateModel(dataContextType);
                Interlocked.CompareExchange(ref primaryModel, model, null);
            }

            // if the primary one matches, use it!
            if (primaryModel.ContextType == dataContextType)
            {
                return(primaryModel);
            }

            // the rest of this only happens if you are using the mapping source for
            // more than one context type

            // build a map if one is not already defined
            if (secondaryModels == null)
            {
                Interlocked.CompareExchange(ref secondaryModels, new Dictionary <Type, MetaModel>(), null);
            }

            // if we haven't created a read/writer lock, make one now
            if (rwlock == null)
            {
                Interlocked.CompareExchange(ref rwlock, new ReaderWriterLock(), null);
            }

            // lock the map and look inside
            MetaModel foundModel;

            rwlock.AcquireReaderLock(Timeout.Infinite);
            try
            {
                if (secondaryModels.TryGetValue(dataContextType, out foundModel))
                {
                    return(foundModel);
                }
            }
            finally
            {
                rwlock.ReleaseReaderLock();
            }

            // if it wasn't found, lock for write and try again
            rwlock.AcquireWriterLock(Timeout.Infinite);
            try
            {
                if (secondaryModels.TryGetValue(dataContextType, out foundModel))
                {
                    return(foundModel);
                }
                if (model == null)
                {
                    model = CreateModel(dataContextType);
                }
                secondaryModels.Add(dataContextType, model);
            }
            finally
            {
                rwlock.ReleaseWriterLock();
            }
            return(model);
        }
Exemplo n.º 20
0
 internal UnmappedType(MetaModel model, Type type) {
     this.model = model;
     this.type = type;
 }
Exemplo n.º 21
0
 internal SqlBinder(Translator translator, SqlFactory sqlFactory, MetaModel model, DataLoadOptions shape, SqlColumnizer columnizer, bool canUseOuterApply) {
     this.sql = sqlFactory;
     this.columnizer = columnizer;
     this.visitor = new Visitor(this, translator, this.columnizer, this.sql, model, shape, canUseOuterApply);
 }
Exemplo n.º 22
0
        private string DeleteDatabaseSQL(
            MetaModel model)
        {
            StringBuilder commandBuilder = new StringBuilder();

            // Append the SQL for deleting the tables
            foreach (MetaTable table in model.GetTables())
            {
                commandBuilder.Append(m_builder.DeleteTableSQL(table));
                commandBuilder.Append("\r\n");
            }

            return commandBuilder.ToString();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Returns a list of all modified properties since last Register/ClearModified
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="metaModel"></param>
        /// <returns></returns>
        public IList<MemberInfo> GetModifiedProperties(object entity, MetaModel metaModel)
        {
            if (IsNotifying(entity))
                return GetNotifyingModifiedProperties(entity, metaModel);

            return GetRawModifiedProperties(entity, metaModel);
        }
Exemplo n.º 24
0
 internal SqlFactory(TypeSystemProvider typeProvider, MetaModel model) {
     this.typeProvider = typeProvider;
     this.model = model;
 }
Exemplo n.º 25
0
			public DataBossTable(MetaModel model, Type rowType) {
				this.model = model;
				this.rowType = rowType;
			}
Exemplo n.º 26
0
 /// <summary>
 /// Gets all column properties.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <param name="metaModel">The meta model.</param>
 /// <returns></returns>
 protected IList<MemberInfo> GetAllColumnProperties(object entity, MetaModel metaModel)
 {
     if (entity == null)
         throw new ArgumentNullException("entity");
     var properties = new List<MemberInfo>(GetColumnMembers(entity.GetType(), metaModel));
     return properties;
 }
Exemplo n.º 27
0
 /// <summary>
 /// Gets the self declaring entity modified properties.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <param name="metaModel">The meta model.</param>
 /// <returns></returns>
 protected IList<MemberInfo> GetSelfDeclaringModifiedProperties(object entity, MetaModel metaModel)
 {
     return GetAllColumnProperties(entity, metaModel);
 }
Exemplo n.º 28
0
 /// <summary>
 /// Sets the raw entity as unmodified.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <param name="metaModel">The meta model.</param>
 private void ClearRawModified(object entity, MetaModel metaModel)
 {
     rawDataEntities[entity] = GetEntityRawData(entity, metaModel);
 }
Exemplo n.º 29
0
 /// <summary>
 /// Gets the notifying entity modified properties.
 /// </summary>
 /// <param name="entity">The entity.</param>
 /// <param name="metaModel">The meta model.</param>
 /// <returns></returns>
 protected IList<MemberInfo> GetNotifyingModifiedProperties(object entity, MetaModel metaModel)
 {
     IDictionary<string, MemberInfo> properties;
     // if we don't have it, it is fully dirty
     if (!modifiedProperties.TryGetValue(entity, out properties) || 
             ReferenceEquals(propertyChangingSentinal, modifiedProperties[entity]))
         return GetAllColumnProperties(entity, metaModel);
     return new List<MemberInfo>(properties.Values);
 }
Exemplo n.º 30
0
 internal Visitor(TypeSystemProvider typeProvider, MetaModel model) {
     this.sql = new SqlFactory(typeProvider, model);
     this.typeProvider = typeProvider;
 }
Exemplo n.º 31
0
 internal SqlRetyper(TypeSystemProvider typeProvider, MetaModel model) {
     this.visitor = new Visitor(typeProvider, model);
 }
Exemplo n.º 32
0
 /// <summary>
 /// Marks the entity as not dirty.
 /// </summary>
 /// <param name="entity"></param>
 /// <param name="metaModel"></param>
 public void ClearModified(object entity, MetaModel metaModel)
 {
     if (IsNotifying(entity))
         ClearNotifyingModified(entity);
     else
         ClearRawModified(entity, metaModel);
 }