internal SerializableImplementor(EntityType ospaceEntityType)
        {
            _baseClrType = ospaceEntityType.ClrType;
            _baseImplementsISerializable = _baseClrType.IsSerializable && typeof(ISerializable).IsAssignableFrom(_baseClrType);

            if (_baseImplementsISerializable)
            {
                // Determine if interface implementation can be overridden.
                // Fortunately, there's only one method to check.
                var mapping = _baseClrType.GetInterfaceMap(typeof(ISerializable));
                _getObjectDataMethod = mapping.TargetMethods[0];

                // Members that implement interfaces must be public, unless they are explicitly implemented, in which case they are private and sealed (at least for C#).
                var canOverrideMethod = (_getObjectDataMethod.IsVirtual && !_getObjectDataMethod.IsFinal) && _getObjectDataMethod.IsPublic;

                if (canOverrideMethod)
                {
                    // Determine if proxied type provides the special serialization constructor.
                    // In order for the proxy class to properly support ISerializable, this constructor must not be private.
                    _serializationConstructor =
                        _baseClrType.GetConstructor(
                            BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null,
                            new[] { typeof(SerializationInfo), typeof(StreamingContext) }, null);

                    _canOverride = _serializationConstructor != null
                                   &&
                                   (_serializationConstructor.IsPublic || _serializationConstructor.IsFamily
                                    || _serializationConstructor.IsFamilyOrAssembly);
                }

                Debug.Assert(
                    !(_canOverride && (_getObjectDataMethod == null || _serializationConstructor == null)),
                    "Both GetObjectData method and Serialization Constructor must be present when proxy overrides ISerializable implementation.");
            }
        }
示例#2
0
        public void AddEntityTypeMappingFragment(
            EntitySet entitySet, EntityType entityType, MappingFragment fragment)
        {
            Debug.Assert(fragment.Table == Table);

            _entityTypes.Add(entitySet, entityType);

            var defaultDiscriminatorColumn = fragment.GetDefaultDiscriminator();

            foreach (var cm in fragment.ColumnMappings)
            {
                var columnMapping = FindOrCreateColumnMapping(cm.ColumnProperty);
                columnMapping.AddMapping(
                    entityType,
                    cm.PropertyPath,
                    fragment.ColumnConditions.Where(cc => cc.Column == cm.ColumnProperty),
                    defaultDiscriminatorColumn == cm.ColumnProperty);
            }

            // Add any column conditions that aren't mapped to properties
            foreach (
                var cc in
                    fragment.ColumnConditions.Where(cc => fragment.ColumnMappings.All(pm => pm.ColumnProperty != cc.Column)))
            {
                var columnMapping = FindOrCreateColumnMapping(cc.Column);
                columnMapping.AddMapping(entityType, null, new[] { cc }, defaultDiscriminatorColumn == cc.Column);
            }
        }
        public static void SyncNullabilityCSSpace(
            this ColumnMappingBuilder propertyMappingBuilder,
            DbDatabaseMapping databaseMapping,
            IEnumerable<EntitySet> entitySets,
            EntityType toTable)
        {
            DebugCheck.NotNull(propertyMappingBuilder);

            var property = propertyMappingBuilder.PropertyPath.Last();

            EntitySetMapping setMapping = null;

            var baseType = (EntityType)property.DeclaringType.BaseType;
            if (baseType != null)
            {
                setMapping = GetEntitySetMapping(databaseMapping, baseType, entitySets);
            }

            while (baseType != null)
            {
                if (toTable == setMapping.EntityTypeMappings.First(m => m.EntityType == baseType).GetPrimaryTable())
                {
                    // CodePlex 2254: If current table is part of TPH mapping below the TPT mapping we are processing, then
                    // don't change the nullability because the TPH nullability calculated previously is still correct.
                    return;
                }

                baseType = (EntityType)baseType.BaseType;
            }

            propertyMappingBuilder.ColumnProperty.Nullable = property.Nullable;
        }
        /// <inheritdoc/>
        protected override bool MatchDependentKeyProperty(
            AssociationType associationType,
            AssociationEndMember dependentAssociationEnd,
            EdmProperty dependentProperty,
            EntityType principalEntityType,
            EdmProperty principalKeyProperty)
        {
            Check.NotNull(associationType, "associationType");
            Check.NotNull(dependentAssociationEnd, "dependentAssociationEnd");
            Check.NotNull(dependentProperty, "dependentProperty");
            Check.NotNull(principalEntityType, "principalEntityType");
            Check.NotNull(principalKeyProperty, "principalKeyProperty");

            var otherEnd = associationType.GetOtherEnd(dependentAssociationEnd);

            var navigationProperty
                = dependentAssociationEnd.GetEntityType().NavigationProperties
                                         .SingleOrDefault(n => n.ResultEnd == otherEnd);

            if (navigationProperty == null)
            {
                return false;
            }

            return string.Equals(
                dependentProperty.Name, navigationProperty.Name + principalKeyProperty.Name,
                StringComparison.OrdinalIgnoreCase);
        }
        public void Generate_should_flatten_complex_properties_to_columns()
        {
            var databaseMapping = CreateEmptyModel();
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var complexType = new ComplexType("C");

            var property = EdmProperty.Primitive("P1", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            complexType.AddMember(property);
            entityType.AddComplexProperty("C1", complexType);
            var property1 = EdmProperty.Primitive("P2", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));

            entityType.AddMember(property1);
            var entitySet = databaseMapping.Model.AddEntitySet("ESet", entityType);
            var type = typeof(object);

            entityType.Annotations.SetClrType(type);

            new TableMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest).Generate(entityType, databaseMapping);

            var entityTypeMappingFragment
                = databaseMapping.GetEntitySetMapping(entitySet).EntityTypeMappings.Single().MappingFragments.Single();

            Assert.Equal(2, entityTypeMappingFragment.ColumnMappings.Count());
            Assert.Equal(2, entityTypeMappingFragment.Table.Properties.Count());
        }
        public void Cannot_create_with_null_argument()
        {
            var entityType = new EntityType("ET", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", "S", "T", "Q", entityType);
            var function = new EdmFunction("F", "N", DataSpace.SSpace, new EdmFunctionPayload());
            var parameterBindings = Enumerable.Empty<ModificationFunctionParameterBinding>();
            var rowsAffectedParameter = new FunctionParameter("rows_affected", new TypeUsage(), ParameterMode.Out);
            var resultBindings = Enumerable.Empty<ModificationFunctionResultBinding>();

            Assert.Equal(
                "entitySet",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMapping(
                        null, entityType, function, 
                        parameterBindings, rowsAffectedParameter, resultBindings)).ParamName);

            Assert.Equal(
                "function",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMapping(
                        entitySet, entityType, null,
                        parameterBindings, rowsAffectedParameter, resultBindings)).ParamName);

            Assert.Equal(
                "parameterBindings",
                Assert.Throws<ArgumentNullException>(
                    () => new ModificationFunctionMapping(
                        entitySet, entityType, function,
                        null, rowsAffectedParameter, resultBindings)).ParamName);
        }
        public void Create_throws_argument_exception_when_called_with_invalid_arguments()
        {
            var entityType = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var refType = new RefType(entityType);
            var metadataProperty =
                new MetadataProperty(
                    "MetadataProperty",
                    TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    "value");

            Assert.Throws<ArgumentException>(
                () => AssociationEndMember.Create(
                    null,
                    refType,
                    RelationshipMultiplicity.Many,
                    OperationAction.Cascade,
                    new[] { metadataProperty }));

            Assert.Throws<ArgumentException>(
                () => AssociationEndMember.Create(
                    String.Empty,
                    refType,
                    RelationshipMultiplicity.Many,
                    OperationAction.Cascade,
                    new[] { metadataProperty }));

            Assert.Throws<ArgumentNullException>(
                () => AssociationEndMember.Create(
                    "AssociationEndMember",
                    null,
                    RelationshipMultiplicity.Many,
                    OperationAction.Cascade,
                    new[] { metadataProperty }));
        }
        public void Can_retrieve_properties()
        {
            var source = new EntityType("Source", "N", DataSpace.CSpace);
            var target = new EntityType("Target", "N", DataSpace.CSpace);
            var sourceEnd = new AssociationEndMember("SourceEnd", source);
            var targetEnd = new AssociationEndMember("TargetEnd", target);
            var associationType 
                = AssociationType.Create(
                    "AT",
                    "N",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    null,
                    null);
            var sourceSet = new EntitySet("SourceSet", "S", "T", "Q", source);
            var targetSet = new EntitySet("TargetSet", "S", "T", "Q", target);
            var associationSet
                = AssociationSet.Create(
                    "AS",
                    associationType,
                    sourceSet,
                    targetSet,
                    null);

            var members = new List<EdmMember> { null, targetEnd };
            var memberPath = new ModificationFunctionMemberPath(members, associationSet);

            Assert.Equal(members, memberPath.Members);
            Assert.Equal(targetEnd.Name, memberPath.AssociationSetEnd.Name);
        }
        public static EdmProperty IncludeColumn(
            EntityType table, EdmProperty templateColumn, Func<EdmProperty, bool> isCompatible, bool useExisting)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(templateColumn);

            var existingColumn = table.Properties.FirstOrDefault(isCompatible);

            if (existingColumn == null)
            {
                templateColumn = templateColumn.Clone();
            }
            else if (!useExisting
                     && !existingColumn.IsPrimaryKeyColumn)
            {
                templateColumn = templateColumn.Clone();
            }
            else
            {
                templateColumn = existingColumn;
            }

            AddColumn(table, templateColumn);

            return templateColumn;
        }
        // <summary>
        // Add a new entry to the entityTypeToSet map
        // </summary>
        // <param name="entityType"> entity type </param>
        // <param name="entitySet"> entityset producing this type </param>
        private void AddEntityTypeToSetEntry(md.EntityType entityType, md.EntitySet entitySet)
        {
            md.EntitySet other;
            var          rootType           = GetRootType(entityType);
            var          hasSingleEntitySet = true;

            if (entitySet == null)
            {
                hasSingleEntitySet = false;
            }
            else if (m_entityTypeToEntitySetMap.TryGetValue(rootType, out other))
            {
                if (other != entitySet)
                {
                    hasSingleEntitySet = false;
                }
            }

            if (hasSingleEntitySet)
            {
                m_entityTypeToEntitySetMap[rootType] = entitySet;
            }
            else
            {
                m_entityTypeToEntitySetMap[rootType] = null;
            }
        }
        public void Apply_should_not_match_key_that_is_also_an_fk()
        {
            var model = new EdmModel(DataSpace.CSpace);
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var property = EdmProperty.CreatePrimitive("P", PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int64));

            entityType.AddKeyMember(property);

            var associationType
                = model.AddAssociationType(
                    "A", new EntityType("E", "N", DataSpace.CSpace), RelationshipMultiplicity.ZeroOrOne,
                    entityType, RelationshipMultiplicity.Many);

            associationType.Constraint
                = new ReferentialConstraint(
                    associationType.SourceEnd,
                    associationType.TargetEnd,
                    new[] { property },
                    new[] { property });

            (new StoreGeneratedIdentityKeyConvention())
                .Apply(entityType, new DbModel(model, null));

            Assert.Null(entityType.KeyProperties.Single().GetStoreGeneratedPattern());
        }
示例#12
0
 public static bool HasCascadeDeletePath(
     this EdmModel model,
     System.Data.Entity.Core.Metadata.Edm.EntityType sourceEntityType,
     System.Data.Entity.Core.Metadata.Edm.EntityType targetEntityType)
 {
     return(model.AssociationTypes.SelectMany((Func <AssociationType, IEnumerable <AssociationEndMember> >)(a => a.Members.Cast <AssociationEndMember>()), (a, ae) => new
     {
         a = a,
         ae = ae
     }).Where(_param1 =>
     {
         if (_param1.ae.GetEntityType() == sourceEntityType)
         {
             return _param1.ae.DeleteBehavior == OperationAction.Cascade;
         }
         return false;
     }).Select(_param0 => _param0.a.GetOtherEnd(_param0.ae).GetEntityType()).Any <System.Data.Entity.Core.Metadata.Edm.EntityType>((Func <System.Data.Entity.Core.Metadata.Edm.EntityType, bool>)(et =>
     {
         if (et != targetEntityType)
         {
             return model.HasCascadeDeletePath(et, targetEntityType);
         }
         return true;
     })));
 }
        public static void SetKeyNamesType(this EntityType table, EntityType entityType)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(entityType);

            table.Annotations.SetAnnotation(KeyNamesTypeAnnotation, entityType);
        }
示例#14
0
        public void AddEntityTypeMappingFragment(
            EntitySet entitySet, EntityType entityType, StorageMappingFragment fragment)
        {
            Debug.Assert(fragment.Table == Table);

            _entityTypes.Add(entitySet, entityType);

            var defaultDiscriminatorColumn = fragment.GetDefaultDiscriminator();
            StorageConditionPropertyMapping defaultDiscriminatorCondition = null;
            if (defaultDiscriminatorColumn != null)
            {
                defaultDiscriminatorCondition =
                    fragment.ColumnConditions.SingleOrDefault(cc => cc.ColumnProperty == defaultDiscriminatorColumn);
            }

            foreach (var pm in fragment.ColumnMappings)
            {
                var columnMapping = FindOrCreateColumnMapping(pm.ColumnProperty);
                columnMapping.AddMapping(
                    entityType,
                    pm.PropertyPath,
                    fragment.ColumnConditions.Where(cc => cc.ColumnProperty == pm.ColumnProperty),
                    defaultDiscriminatorColumn == pm.ColumnProperty);
            }

            // Add any column conditions that aren't mapped to properties
            foreach (
                var cc in
                    fragment.ColumnConditions.Where(cc => !fragment.ColumnMappings.Any(pm => pm.ColumnProperty == cc.ColumnProperty)))
            {
                var columnMapping = FindOrCreateColumnMapping(cc.ColumnProperty);
                columnMapping.AddMapping(entityType, null, new[] { cc }, defaultDiscriminatorColumn == cc.ColumnProperty);
            }
        }
        public static void Create_sets_properties_and_seals_the_instance()
        {
            var typeUsage = TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String));
            var associationType = new AssociationType("AssociationType", "Namespace", true, DataSpace.CSpace);
            var source = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd = new AssociationEndMember("SourceEnd", source);
            var targetEnd = new AssociationEndMember("TargetEnd", target);            

            var navigationProperty =
                NavigationProperty.Create(
                    "NavigationProperty",
                    typeUsage,
                    associationType,
                    sourceEnd,
                    targetEnd,
                    new[]
                        {
                            new MetadataProperty(
                                "TestProperty",
                                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                                "value"),
                        });

            Assert.Equal("NavigationProperty", navigationProperty.Name);
            Assert.Same(typeUsage, navigationProperty.TypeUsage);
            Assert.Same(associationType, navigationProperty.RelationshipType);
            Assert.Same(sourceEnd, navigationProperty.FromEndMember);
            Assert.Same(targetEnd, navigationProperty.ToEndMember);
            Assert.True(navigationProperty.IsReadOnly);

            var metadataProperty = navigationProperty.MetadataProperties.SingleOrDefault(p => p.Name == "TestProperty");
            Assert.NotNull(metadataProperty);
            Assert.Equal("value", metadataProperty.Value);
        }
        private static ModuleBuilder GetDynamicModule(EntityType ospaceEntityType)
        {
            var assembly = ospaceEntityType.ClrType.Assembly;
            ModuleBuilder moduleBuilder;
            if (!_moduleBuilders.TryGetValue(assembly, out moduleBuilder))
            {
                var assemblyName =
                    new AssemblyName(String.Format(CultureInfo.InvariantCulture, "EntityFrameworkDynamicProxies-{0}", assembly.FullName));
                assemblyName.Version = new Version(1, 0, 0, 0);

                var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(
                    assemblyName, s_ProxyAssemblyBuilderAccess);

                if (s_ProxyAssemblyBuilderAccess == AssemblyBuilderAccess.RunAndSave)
                {
                    // Make the module persistable if the AssemblyBuilderAccess is changed to be RunAndSave.
                    moduleBuilder = assemblyBuilder.DefineDynamicModule("EntityProxyModule", "EntityProxyModule.dll");
                }
                else
                {
                    moduleBuilder = assemblyBuilder.DefineDynamicModule("EntityProxyModule");
                }

                _moduleBuilders.Add(assembly, moduleBuilder);
            }
            return moduleBuilder;
        }
示例#17
0
        public void Can_set_owner_and_corresponding_association_added_to_model()
        {
            var database
                = new EdmModel
                      {
                          Version = 3.0
                      }.DbInitialize();
            var foreignKeyBuilder = new ForeignKeyBuilder(database, "FK");

            var principalTable = new EntityType("P", XmlConstants.TargetNamespace_3, DataSpace.SSpace);

            foreignKeyBuilder.PrincipalTable = principalTable;

            var dependentTable = new EntityType("D", XmlConstants.TargetNamespace_3, DataSpace.SSpace);

            foreignKeyBuilder.SetOwner(dependentTable);

            var associationType = database.GetAssociationType("FK");

            Assert.NotNull(associationType);
            Assert.NotNull(associationType.SourceEnd);
            Assert.NotNull(associationType.TargetEnd);
            Assert.Same(principalTable, associationType.SourceEnd.GetEntityType());
            Assert.Equal("P", associationType.SourceEnd.Name);
            Assert.Same(dependentTable, associationType.TargetEnd.GetEntityType());
            Assert.Equal("D", associationType.TargetEnd.Name);

            var associationSet = database.GetAssociationSet(associationType);

            Assert.NotNull(associationSet);
        }
示例#18
0
 internal RefType(EntityType entityType)
     : base(GetIdentity(Check.NotNull(entityType, "entityType")),
         EdmConstants.TransientNamespace, entityType.DataSpace)
 {
     _elementType = entityType;
     SetReadOnly();
 }
示例#19
0
        public static void ReplaceEntitySet(
            this EdmModel model,
            System.Data.Entity.Core.Metadata.Edm.EntityType entityType,
            EntitySet newSet)
        {
            EntityContainer entityContainer = model.Containers.Single <EntityContainer>();
            EntitySet       entitySet       = entityContainer.EntitySets.SingleOrDefault <EntitySet>((Func <EntitySet, bool>)(a => a.ElementType == entityType));

            if (entitySet == null)
            {
                return;
            }
            entityContainer.RemoveEntitySetBase((EntitySetBase)entitySet);
            if (newSet == null)
            {
                return;
            }
            foreach (AssociationSet associationSet in model.Containers.Single <EntityContainer>().AssociationSets)
            {
                if (associationSet.SourceSet == entitySet)
                {
                    associationSet.SourceSet = newSet;
                }
                if (associationSet.TargetSet == entitySet)
                {
                    associationSet.TargetSet = newSet;
                }
            }
        }
        public void Can_clear_modification_function_mappings()
        {
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("S", "N", null, null, entityType);
            var function = new EdmFunction("F", "N", DataSpace.SSpace, new EdmFunctionPayload());

            var container = new EntityContainer("C", DataSpace.CSpace);
            container.AddEntitySetBase(entitySet);

            var entitySetMapping =
                new StorageEntitySetMapping(
                    entitySet,
                    new StorageEntityContainerMapping(container));

            var functionMapping =
                new StorageModificationFunctionMapping(
                    entitySet,
                    entityType,
                    function,
                    Enumerable.Empty<StorageModificationFunctionParameterBinding>(),
                    null,
                    null);

            var entityFunctionMappings =
                new StorageEntityTypeModificationFunctionMapping(entityType, functionMapping, null, null);

            entitySetMapping.AddModificationFunctionMapping(entityFunctionMappings);

            Assert.Equal(1, entitySetMapping.ModificationFunctionMappings.Count());

            entitySetMapping.ClearModificationFunctionMappings();

            Assert.Equal(0, entitySetMapping.ModificationFunctionMappings.Count());
        }
        public static EdmProperty IncludeColumn(
            EntityType table, EdmProperty templateColumn, bool useExisting)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(templateColumn);

            var existingColumn =
                table.Properties.SingleOrDefault(c => string.Equals(c.Name, templateColumn.Name, StringComparison.Ordinal));

            if (existingColumn == null)
            {
                templateColumn = templateColumn.Clone();
            }
            else if (!useExisting
                     && !existingColumn.IsPrimaryKeyColumn)
            {
                templateColumn = templateColumn.Clone();
            }
            else
            {
                templateColumn = existingColumn;
            }

            AddColumn(table, templateColumn);

            return templateColumn;
        }
        public void Map_should_create_association_sets_for_associations()
        {
            var modelConfiguration = new ModelConfiguration();
            var model = new EdmModel().Initialize();
            var entityType = new EntityType
                                 {
                                     Name = "Source"
                                 };
            model.AddEntitySet("Source", entityType);

            var mappingContext = new MappingContext(modelConfiguration, new ConventionsConfiguration(), model);

            new NavigationPropertyMapper(new TypeMapper(mappingContext))
                .Map(
                    new MockPropertyInfo(new MockType("Target"), "Nav"), entityType,
                    () => new EntityTypeConfiguration(typeof(object)));

            Assert.Equal(1, model.Containers.Single().AssociationSets.Count);

            var associationSet = model.Containers.Single().AssociationSets.Single();

            Assert.NotNull(associationSet);
            Assert.NotNull(associationSet.ElementType);
            Assert.Equal("Source_Nav", associationSet.Name);
        }
示例#23
0
        /// <summary>
        ///     Gets the list of "identity" properties for an entity. Gets the
        ///     "entitysetid" property in addition to the "key" properties
        /// </summary>
        /// <param name="type"> </param>
        /// <returns> </returns>
        private static PropertyRefList GetIdentityProperties(md.EntityType type)
        {
            var desiredProperties = GetKeyProperties(type);

            desiredProperties.Add(EntitySetIdPropertyRef.Instance);
            return(desiredProperties);
        }
示例#24
0
        public static void SetKeyNamesType(this EntityType table, EntityType entityType)
        {
            DebugCheck.NotNull(table);
            DebugCheck.NotNull(entityType);

            table.GetMetadataProperties().SetAnnotation(KeyNamesTypeAnnotation, entityType);
        }
        public void Add(EntitySet entitySet, EntityType entityType)
        {
            DebugCheck.NotNull(entitySet);
            DebugCheck.NotNull(entityType);

            var i = 0;

            List<EntityType> entityTypes;
            if (!_entityTypes.TryGetValue(entitySet, out entityTypes))
            {
                entityTypes = new List<EntityType>();
                _entityTypes.Add(entitySet, entityTypes);
            }

            for (; i < entityTypes.Count; i++)
            {
                if (entityTypes[i] == entityType)
                {
                    return;
                }
                else if (entityType.IsAncestorOf(entityTypes[i]))
                {
                    break;
                }
            }
            entityTypes.Insert(i, entityType);
        }
        public void WriteMappingFragment_should_write_store_entity_set_name()
        {
            var fixture = new Fixture();

            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", "S", null, null, entityType);
            var entityContainer = new EntityContainer("EC", DataSpace.SSpace);

            entityContainer.AddEntitySetBase(entitySet);

            var storageEntitySetMapping
                = new EntitySetMapping(
                    entitySet,
                    new EntityContainerMapping(entityContainer));

            TypeMapping typeMapping = new EntityTypeMapping(storageEntitySetMapping);

            var mappingFragment = new MappingFragment(entitySet, typeMapping, false);

            fixture.Writer.WriteMappingFragmentElement(mappingFragment);

            Assert.Equal(
                @"<MappingFragment StoreEntitySet=""ES"" />",
                fixture.ToString());
        }
 /// <summary>
 /// Creates a new instance
 /// </summary>
 /// <param name="context">The linq to entities context owning this entity</param>
 /// <param name="entityType">The entity type in the EDM model</param>
 /// <param name="type">The CLR type of the entity</param>
 public LinqToEntitiesEntity(LinqToEntitiesContextBase context, EntityType entityType, Type type)
     : base(context, entityType.Name, type)
 {
     this._hasTimestampMember = entityType.Members.Where(p => ObjectContextUtilities.IsConcurrencyTimestamp(p)).Count() == 1;
     this._entityType = entityType;
     this._isDbContext = context is LinqToEntitiesDbContext;
 }
示例#28
0
        public void Create_factory_method_sets_properties_and_seals_the_type()
        {
            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            var entitySet =
                EntitySet.Create(
                    "EntitySet",
                    "dbo",
                    "tblEntities",
                    "definingQuery",
                    entityType,
                    new[]
                        {
                            new MetadataProperty(
                                "TestProperty",
                                TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                                "value")
                        });

            Assert.Equal("EntitySet", entitySet.Name);
            Assert.Equal("dbo", entitySet.Schema);
            Assert.Equal("tblEntities", entitySet.Table);
            Assert.Equal("definingQuery", entitySet.DefiningQuery);
            Assert.Same(entityType, entitySet.ElementType);

            var metadataProperty = entitySet.MetadataProperties.SingleOrDefault(p => p.Name == "TestProperty");
            Assert.NotNull(metadataProperty);
            Assert.Equal("value", metadataProperty.Value);

            Assert.True(entitySet.IsReadOnly);
        }
        public void Can_not_create_composable_function_import_mapping_with_entity_set_and_null_structural_type_mappings()
        {
            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet = new EntitySet("ES", null, null, null, entityType);

            var functionImport =
                new EdmFunction(
                    "f",
                    "entityModel",
                    DataSpace.CSpace,
                    new EdmFunctionPayload
                        {
                            IsComposable = true,
                            EntitySets = new[] { entitySet },
                            ReturnParameters =
                                new[]
                                    {
                                        new FunctionParameter(
                                            "ReturnType", 
                                            TypeUsage.CreateDefaultTypeUsage(entityType), 
                                            ParameterMode.ReturnValue)
                                    }
                        });

            Assert.Equal(
                Strings.ComposableFunctionImportsReturningEntitiesNotSupported,
                Assert.Throws<NotSupportedException>(
                    () => new FunctionImportMappingComposable(
                              functionImport,
                              new EdmFunction(
                              "f", "store", DataSpace.CSpace, new EdmFunctionPayload { IsComposable = true }),
                              null)).Message);
        }
        public virtual void SetOwner(EntityType owner)
        {
            Util.ThrowIfReadOnly(this);

            if (owner == null)
            {
                _database.RemoveAssociationType(_associationType);
            }
            else
            {
                _associationType.TargetEnd
                    = new AssociationEndMember(
                        owner != PrincipalTable ? owner.Name : owner.Name + SelfRefSuffix,
                        owner);

                _associationSet.TargetSet
                    = _database.GetEntitySet(owner);

                if (!_database.AssociationTypes.Contains(_associationType))
                {
                    _database.AddAssociationType(_associationType);
                    _database.AddAssociationSet(_associationSet);
                }
            }
        }
        /// <inheritdoc/>
        protected override IEnumerable<EdmProperty> MatchKeyProperty(
            EntityType entityType, IEnumerable<EdmProperty> primitiveProperties)
        {
            Check.NotNull(entityType, "entityType");
            Check.NotNull(primitiveProperties, "primitiveProperties");

            var matches = primitiveProperties
                .Where(p => Id.Equals(p.Name, StringComparison.OrdinalIgnoreCase));

            if (!matches.Any())
            {
                matches = primitiveProperties
                    .Where(p => (entityType.Name + Id).Equals(p.Name, StringComparison.OrdinalIgnoreCase));
            }

            // If the number of matches is more than one, then multiple properties matched differing only by
            // case--for example, "Id" and "ID". In such as case we throw and point the developer to using
            // data annotations or the fluent API to disambiguate.
            if (matches.Count() > 1)
            {
                throw Error.MultiplePropertiesMatchedAsKeys(matches.First().Name, entityType.Name);
            }

            return matches;
        }
        public bool Contains(EntitySet entitySet, EntityType entityType)
        {
            DebugCheck.NotNull(entitySet);
            DebugCheck.NotNull(entityType);

            List<EntityType> setTypes;
            return _entityTypes.TryGetValue(entitySet, out setTypes) && setTypes.Contains(entityType);
        }
        public void Can_get_and_set_configuration_annotation()
        {
            var entityType = new EntityType("E", "N", DataSpace.CSpace);

            entityType.Annotations.SetConfiguration(42);

            Assert.Equal(42, entityType.GetConfiguration());
        }
示例#34
0
        public TableMapping(EntityType table)
        {
            DebugCheck.NotNull(table);

            _table = table;
            _entityTypes = new SortedEntityTypeIndex();
            _columns = new List<ColumnMapping>();
        }
示例#35
0
        private Type GetNavigationTargetType(NavigationProperty navigationProperty)
        {
            MetadataWorkspace metadataWorkspace = this._internalContext.ObjectContext.MetadataWorkspace;

            System.Data.Entity.Core.Metadata.Edm.EntityType entityType = navigationProperty.RelationshipType.RelationshipEndMembers.Single <RelationshipEndMember>((Func <RelationshipEndMember, bool>)(e => navigationProperty.ToEndMember.Name == e.Name)).GetEntityType();
            StructuralType objectSpaceType = metadataWorkspace.GetObjectSpaceType((StructuralType)entityType);

            return(((ObjectItemCollection)metadataWorkspace.GetItemCollection(DataSpace.OSpace)).GetClrType(objectSpaceType));
        }
示例#36
0
        public static IEnumerable <System.Data.Entity.Core.Metadata.Edm.EntityType> GetSelfAndAllDerivedTypes(
            this EdmModel model,
            System.Data.Entity.Core.Metadata.Edm.EntityType entityType)
        {
            List <System.Data.Entity.Core.Metadata.Edm.EntityType> entityTypes = new List <System.Data.Entity.Core.Metadata.Edm.EntityType>();

            EdmModelExtensions.AddSelfAndAllDerivedTypes(model, entityType, entityTypes);
            return((IEnumerable <System.Data.Entity.Core.Metadata.Edm.EntityType>)entityTypes);
        }
示例#37
0
 public static System.Data.Entity.Core.Metadata.Edm.EntityType AddEntityType(
     this EdmModel model,
     string name,
     string modelNamespace = null)
 {
     System.Data.Entity.Core.Metadata.Edm.EntityType entityType = new System.Data.Entity.Core.Metadata.Edm.EntityType(name, modelNamespace ?? "CodeFirstNamespace", DataSpace.CSpace);
     model.AddItem(entityType);
     return(entityType);
 }
示例#38
0
        private static EntitySetBase GetEntitySet(EntityContainer container, EFEntityType entityType)
        {
            var baseType = entityType;

            while (baseType?.BaseType != null)
            {
                baseType = baseType.BaseType as EFEntityType;
            }
            return(container.BaseEntitySets.First(set => set.ElementType == baseType));
        }
示例#39
0
        public static EntitySet AddEntitySet(
            this EdmModel model,
            string name,
            System.Data.Entity.Core.Metadata.Edm.EntityType elementType,
            string table = null)
        {
            EntitySet entitySet = new EntitySet(name, (string)null, table, (string)null, elementType);

            model.Containers.Single <EntityContainer>().AddEntitySetBase((EntitySetBase)entitySet);
            return(entitySet);
        }
示例#40
0
 private static void AddSelfAndAllDerivedTypes(
     EdmModel model,
     System.Data.Entity.Core.Metadata.Edm.EntityType entityType,
     List <System.Data.Entity.Core.Metadata.Edm.EntityType> entityTypes)
 {
     entityTypes.Add(entityType);
     foreach (System.Data.Entity.Core.Metadata.Edm.EntityType entityType1 in model.EntityTypes.Where <System.Data.Entity.Core.Metadata.Edm.EntityType>((Func <System.Data.Entity.Core.Metadata.Edm.EntityType, bool>)(et => et.BaseType == entityType)))
     {
         EdmModelExtensions.AddSelfAndAllDerivedTypes(model, entityType1, entityTypes);
     }
 }
示例#41
0
        public static System.Data.Entity.Core.Metadata.Edm.EntityType AddTable(
            this EdmModel database,
            string name)
        {
            string str = ((IEnumerable <INamedDataModelItem>)database.EntityTypes).UniquifyName(name);

            System.Data.Entity.Core.Metadata.Edm.EntityType elementType = new System.Data.Entity.Core.Metadata.Edm.EntityType(str, "CodeFirstDatabaseSchema", DataSpace.SSpace);
            database.AddItem(elementType);
            database.AddEntitySet(elementType.Name, elementType, str);
            return(elementType);
        }
示例#42
0
        public static void RemoveEntityType(this EdmModel model, System.Data.Entity.Core.Metadata.Edm.EntityType entityType)
        {
            model.RemoveItem(entityType);
            EntityContainer entityContainer = model.Containers.Single <EntityContainer>();
            EntitySet       entitySet       = entityContainer.EntitySets.SingleOrDefault <EntitySet>((Func <EntitySet, bool>)(a => a.ElementType == entityType));

            if (entitySet == null)
            {
                return;
            }
            entityContainer.RemoveEntitySetBase((EntitySetBase)entitySet);
        }
示例#43
0
 public static System.Data.Entity.Core.Metadata.Edm.EntityType AddTable(
     this EdmModel database,
     string name,
     System.Data.Entity.Core.Metadata.Edm.EntityType pkSource)
 {
     System.Data.Entity.Core.Metadata.Edm.EntityType entityType = database.AddTable(name);
     foreach (EdmProperty keyProperty in pkSource.KeyProperties)
     {
         entityType.AddKeyMember((EdmMember)keyProperty.Clone());
     }
     return(entityType);
 }
示例#44
0
        public static EntityTypeMapping GetEntityTypeMapping(
            this DbDatabaseMapping databaseMapping,
            System.Data.Entity.Core.Metadata.Edm.EntityType entityType)
        {
            IList <EntityTypeMapping> entityTypeMappings = databaseMapping.GetEntityTypeMappings(entityType);

            if (entityTypeMappings.Count <= 1)
            {
                return(entityTypeMappings.FirstOrDefault <EntityTypeMapping>());
            }
            return(entityTypeMappings.SingleOrDefault <EntityTypeMapping>((Func <EntityTypeMapping, bool>)(m => m.IsHierarchyMapping)));
        }
示例#45
0
        private static PropertyRefList GetKeyProperties(md.EntityType entityType)
        {
            var desiredProperties = new PropertyRefList();

            foreach (var p in entityType.KeyMembers)
            {
                var edmP = p as md.EdmProperty;
                PlanCompiler.Assert(edmP != null, "EntityType had non-EdmProperty key member?");
                var pRef = new SimplePropertyRef(edmP);
                desiredProperties.Add(pRef);
            }
            return(desiredProperties);
        }
示例#46
0
        private bool TryConvertToEntityTypeConditionsAndPropertyMappings(
            EdmFunction functionImport,
            FunctionImportStructuralTypeMappingKB functionImportKB,
            int typeID,
            RowType cTypeTvfElementType,
            RowType sTypeTvfElementType,
            IXmlLineInfo navLineInfo,
            out List <ConditionPropertyMapping> typeConditions,
            out List <PropertyMapping> propertyMappings)
        {
            System.Data.Entity.Core.Metadata.Edm.EntityType mappedEntityType = functionImportKB.MappedEntityTypes[typeID];
            typeConditions = new List <ConditionPropertyMapping>();
            bool flag = false;

            foreach (FunctionImportNormalizedEntityTypeMapping entityTypeMapping in functionImportKB.NormalizedEntityTypeMappings.Where <FunctionImportNormalizedEntityTypeMapping>((Func <FunctionImportNormalizedEntityTypeMapping, bool>)(f => f.ImpliedEntityTypes[typeID])))
            {
                foreach (FunctionImportEntityTypeMappingCondition mappingCondition in entityTypeMapping.ColumnConditions.Where <FunctionImportEntityTypeMappingCondition>((Func <FunctionImportEntityTypeMappingCondition, bool>)(c => c != null)))
                {
                    FunctionImportEntityTypeMappingCondition condition = mappingCondition;
                    EdmProperty column;
                    if (sTypeTvfElementType.Properties.TryGetValue(condition.ColumnName, false, out column))
                    {
                        object obj;
                        bool?  nullable;
                        if (condition.ConditionValue.IsSentinel)
                        {
                            obj      = (object)null;
                            nullable = condition.ConditionValue != ValueCondition.IsNull ? new bool?(false) : new bool?(true);
                        }
                        else
                        {
                            PrimitiveType edmType = (PrimitiveType)cTypeTvfElementType.Properties[column.Name].TypeUsage.EdmType;
                            obj = ((FunctionImportEntityTypeMappingConditionValue)condition).GetConditionValue(edmType.ClrEquivalentType, (Action)(() => FunctionImportMappingComposableHelper.AddToSchemaErrorWithMemberAndStructure(new Func <object, object, string>(Strings.Mapping_InvalidContent_ConditionMapping_InvalidPrimitiveTypeKind), column.Name, column.TypeUsage.EdmType.FullName, MappingErrorCode.ConditionError, this.m_sourceLocation, (IXmlLineInfo)condition.LineInfo, (IList <EdmSchemaError>) this.m_parsingErrors)), (Action)(() => FunctionImportMappingComposableHelper.AddToSchemaErrors(Strings.Mapping_ConditionValueTypeMismatch, MappingErrorCode.ConditionError, this.m_sourceLocation, (IXmlLineInfo)condition.LineInfo, (IList <EdmSchemaError>) this.m_parsingErrors)));
                            if (obj == null)
                            {
                                flag = true;
                                continue;
                            }
                            nullable = new bool?();
                        }
                        typeConditions.Add(obj != null ? (ConditionPropertyMapping) new ValueConditionMapping(column, obj) : (ConditionPropertyMapping) new IsNullConditionMapping(column, nullable.Value));
                    }
                    else
                    {
                        FunctionImportMappingComposableHelper.AddToSchemaErrorsWithMemberInfo(new Func <object, string>(Strings.Mapping_InvalidContent_Column), condition.ColumnName, MappingErrorCode.InvalidStorageMember, this.m_sourceLocation, (IXmlLineInfo)condition.LineInfo, (IList <EdmSchemaError>) this.m_parsingErrors);
                    }
                }
            }
            return(!(flag | !this.TryConvertToPropertyMappings((StructuralType)mappedEntityType, cTypeTvfElementType, sTypeTvfElementType, functionImport, functionImportKB, navLineInfo, out propertyMappings)));
        }
示例#47
0
        public static System.Data.Entity.Core.Metadata.Edm.EntityType GetEntityType(
            this EdmModel model,
            Type clrType)
        {
            IList <System.Data.Entity.Core.Metadata.Edm.EntityType> entityTypeList = model.EntityTypes as IList <System.Data.Entity.Core.Metadata.Edm.EntityType> ?? (IList <System.Data.Entity.Core.Metadata.Edm.EntityType>)model.EntityTypes.ToList <System.Data.Entity.Core.Metadata.Edm.EntityType>();

            for (int index = 0; index < entityTypeList.Count; ++index)
            {
                System.Data.Entity.Core.Metadata.Edm.EntityType entityType = entityTypeList[index];
                if (EntityTypeExtensions.GetClrType(entityType) == clrType)
                {
                    return(entityType);
                }
            }
            return((System.Data.Entity.Core.Metadata.Edm.EntityType)null);
        }
示例#48
0
        public static System.Data.Entity.Core.Metadata.Edm.EntityType FindTableByName(
            this EdmModel database,
            DatabaseName tableName)
        {
            IList <System.Data.Entity.Core.Metadata.Edm.EntityType> entityTypeList = database.EntityTypes as IList <System.Data.Entity.Core.Metadata.Edm.EntityType> ?? (IList <System.Data.Entity.Core.Metadata.Edm.EntityType>)database.EntityTypes.ToList <System.Data.Entity.Core.Metadata.Edm.EntityType>();

            for (int index = 0; index < entityTypeList.Count; ++index)
            {
                System.Data.Entity.Core.Metadata.Edm.EntityType table = entityTypeList[index];
                DatabaseName tableName1 = table.GetTableName();
                if ((tableName1 != null ? (tableName1.Equals(tableName) ? 1 : 0) : (!string.Equals(table.Name, tableName.Name, StringComparison.Ordinal) ? 0 : (tableName.Schema == null ? 1 : 0))) != 0)
                {
                    return(table);
                }
            }
            return((System.Data.Entity.Core.Metadata.Edm.EntityType)null);
        }
示例#49
0
 public static IEnumerable <AssociationType> GetAssociationTypesBetween(
     this EdmModel model,
     System.Data.Entity.Core.Metadata.Edm.EntityType first,
     System.Data.Entity.Core.Metadata.Edm.EntityType second)
 {
     return(model.AssociationTypes.Where <AssociationType>((Func <AssociationType, bool>)(a =>
     {
         if (a.SourceEnd.GetEntityType() == first && a.TargetEnd.GetEntityType() == second)
         {
             return true;
         }
         if (a.SourceEnd.GetEntityType() == second)
         {
             return a.TargetEnd.GetEntityType() == first;
         }
         return false;
     })));
 }
示例#50
0
        public static AssociationType AddAssociationType(
            this EdmModel model,
            string name,
            System.Data.Entity.Core.Metadata.Edm.EntityType sourceEntityType,
            RelationshipMultiplicity sourceAssociationEndKind,
            System.Data.Entity.Core.Metadata.Edm.EntityType targetEntityType,
            RelationshipMultiplicity targetAssociationEndKind,
            string modelNamespace = null)
        {
            AssociationType associationType = new AssociationType(name, modelNamespace ?? "CodeFirstNamespace", false, DataSpace.CSpace)
            {
                SourceEnd = new AssociationEndMember(name + "_Source", sourceEntityType.GetReferenceType(), sourceAssociationEndKind),
                TargetEnd = new AssociationEndMember(name + "_Target", targetEntityType.GetReferenceType(), targetAssociationEndKind)
            };

            model.AddAssociationType(associationType);
            return(associationType);
        }
示例#51
0
 private static bool TryInferTVFKeysForEntityType(
     System.Data.Entity.Core.Metadata.Edm.EntityType entityType,
     List <PropertyMapping> propertyMappings,
     out EdmProperty[] keys)
 {
     keys = new EdmProperty[entityType.KeyMembers.Count];
     for (int index = 0; index < keys.Length; ++index)
     {
         ScalarPropertyMapping propertyMapping = propertyMappings[entityType.Properties.IndexOf((EdmProperty)entityType.KeyMembers[index])] as ScalarPropertyMapping;
         if (propertyMapping == null)
         {
             keys = (EdmProperty[])null;
             return(false);
         }
         keys[index] = propertyMapping.Column;
     }
     return(true);
 }
示例#52
0
        public static IList <EntityTypeMapping> GetEntityTypeMappings(
            this DbDatabaseMapping databaseMapping,
            System.Data.Entity.Core.Metadata.Edm.EntityType entityType)
        {
            List <EntityTypeMapping> entityTypeMappingList = new List <EntityTypeMapping>();

            foreach (EntitySetMapping entitySetMapping in databaseMapping.EntityContainerMappings.Single <EntityContainerMapping>().EntitySetMappings)
            {
                foreach (EntityTypeMapping entityTypeMapping in entitySetMapping.EntityTypeMappings)
                {
                    if (entityTypeMapping.EntityType == entityType)
                    {
                        entityTypeMappingList.Add(entityTypeMapping);
                    }
                }
            }
            return((IList <EntityTypeMapping>)entityTypeMappingList);
        }
示例#53
0
 private EntityIdentity CreateEntityIdentity(
     md.EntityType entityType,
     SimpleColumnMap entitySetIdColumnMap,
     SimpleColumnMap[] keyColumnMaps)
 {
     //
     // If we have an entitysetid (and therefore, a column map for the entitysetid),
     // then use a discriminated entity identity; otherwise, we use a simpleentityidentity
     // instead
     //
     if (entitySetIdColumnMap != null)
     {
         return(new DiscriminatedEntityIdentity(entitySetIdColumnMap, m_typeInfo.EntitySetIdToEntitySetMap, keyColumnMaps));
     }
     else
     {
         var entitySet = m_typeInfo.GetEntitySet(entityType);
         PlanCompiler.Assert(
             entitySet != null, "Expected non-null entitySet when no entity set ID is required. Entity type = " + entityType);
         return(new SimpleEntityIdentity(entitySet, keyColumnMaps));
     }
 }
        public void Create_throws_argument_exception_when_called_with_invalid_arguments()
        {
            var source     = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target     = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var sourceEnd  = new AssociationEndMember("SourceEnd", source);
            var targetEnd  = new AssociationEndMember("TargetEnd", target);
            var constraint =
                new ReferentialConstraint(
                    sourceEnd,
                    targetEnd,
                    new[] { new EdmProperty("SourceProperty") },
                    new[] { new EdmProperty("TargetProperty") });
            var metadataProperty =
                new MetadataProperty(
                    "MetadataProperty",
                    TypeUsage.CreateDefaultTypeUsage(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.String)),
                    "value");

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    null,
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    String.Empty,
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    "AssociationType",
                    null,
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));

            Assert.Throws <ArgumentException>(
                () => AssociationType.Create(
                    "AssociationType",
                    String.Empty,
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    constraint,
                    new[] { metadataProperty }));
        }
示例#55
0
 public static IEnumerable <System.Data.Entity.Core.Metadata.Edm.EntityType> GetDerivedTypes(
     this EdmModel model,
     System.Data.Entity.Core.Metadata.Edm.EntityType entityType)
 {
     return(model.EntityTypes.Where <System.Data.Entity.Core.Metadata.Edm.EntityType>((Func <System.Data.Entity.Core.Metadata.Edm.EntityType, bool>)(et => et.BaseType == entityType)));
 }
示例#56
0
        public void ScaffoldEntity(EdmType eType)
        {
            System.Data.Entity.Core.Metadata.Edm.EntityType entityType = (System.Data.Entity.Core.Metadata.Edm.EntityType)eType;

            // items in eType
            //FullName - XScaffolding.Models.Customers
            //KeyMembers - pk columns
            //KeyProperties - same
            //Members - columns
            //Properties - same
            //MetadataProperties
            //Name - Customers
            //NamespaceName - XScaffolding.Models
            //NavigationProperties - foreign keys

            // add from entities name in web.config connection strings
            // to do : fix this to create for all connection strings that are EF
            string dbContextName = "NorthwindEntities";
            string pkName        = entityType.KeyMembers[0].Name;
            string pkDataType    = null;
            string modelName     = entityType.Name;

            System.Data.Entity.Design.PluralizationServices.PluralizationService ps = System.Data.Entity.Design.PluralizationServices.PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentCulture);
            string        modelNamePlural      = ps.Pluralize(modelName);
            string        modelNamePluralLower = modelNamePlural.ToLower();
            string        nameSpace            = entityType.NamespaceName;
            List <string> asdf          = nameSpace.Split('.').ToList();
            string        nameSpaceRoot = asdf.First();
            List <string> columnNames   = new List <string>();

            foreach (var v in entityType.Members)
            {
                columnNames.Add(v.Name);
            }

            string   edmxFileName         = @"C:\Users\mwheaton\Documents\Visual Studio 2017\Projects\XScaffolding\XScaffolding\Models\Model1.edmx";
            XElement xfile                = XElement.Load(edmxFileName);
            XElement edmxRuntime          = xfile.Elements().First();
            XElement edmxConceptualModels = edmxRuntime.Elements().Where(m => m.Name.LocalName == "ConceptualModels").First();
            XElement edmxConceptualSchema = edmxConceptualModels.Elements().First();
            IEnumerable <XElement> items  = edmxConceptualSchema.Elements().Where(m => m.Name.LocalName == "EntityType");
            bool found = false;

            foreach (var item in items)
            {
                if (modelName == item.FirstAttribute.Value)
                {
                    pkDataType = "";
                    //pkName = item.Elements().Where(m => m.Name.LocalName == "Key").First().Elements().Where(m => m.Name.LocalName == "PropertyRef").First().FirstAttribute.Value;
                    foreach (XElement xe in item.Elements().Where(m => m.Name.LocalName == "Property")) // skip key and navigation properties
                    {
                        if (xe.FirstAttribute.Value == pkName)
                        {
                            pkDataType = xe.Attribute("Type").Value.StartsWith("Int") ? "int" : "string";
                            found      = true;
                            break;
                        }
                    }
                }
                if (found)
                {
                    break;
                }
            }

            string            outputPath = System.Web.HttpContext.Current.Server.MapPath("~/Output");
            TextFileUtilities xsfUtils   = new TextFileUtilities();

            System.IO.Directory.CreateDirectory(outputPath + @"\Controllers");
            System.IO.Directory.CreateDirectory(outputPath + @"\Views");
            System.IO.Directory.CreateDirectory(outputPath + @"\Views\" + modelNamePlural);

            // write controller
            string controller = LoadTemplateByType(TemplateType.Controller);

            controller = controller.Replace(@"$nameSpace$", nameSpace);
            controller = controller.Replace(@"$nameSpaceRoot$", nameSpaceRoot);
            controller = controller.Replace(@"$dbContextName$", dbContextName);
            controller = controller.Replace(@"$modelName$", modelName);
            controller = controller.Replace(@"$modelVariable$", modelName.ToLower());
            controller = controller.Replace(@"$modelNamePlural$", modelNamePlural);
            controller = controller.Replace(@"$modelNamePluralLower$", modelNamePluralLower);
            controller = controller.Replace(@"$pkName$", pkName);
            xsfUtils.WriteTextFile(outputPath + @"\Controllers\" + modelNamePlural + "Controller.cs", controller);

            string apiController = LoadTemplateByType(TemplateType.ApiController);

            apiController = apiController.Replace(@"$nameSpace$", nameSpace);
            apiController = apiController.Replace(@"$nameSpaceRoot$", nameSpaceRoot);
            apiController = apiController.Replace(@"$dbContextName$", dbContextName);
            apiController = apiController.Replace(@"$modelName$", modelName);
            apiController = apiController.Replace(@"$modelVariable$", modelName.ToLower());
            apiController = apiController.Replace(@"$modelNamePlural$", modelNamePlural);
            apiController = apiController.Replace(@"$modelNamePluralLower$", modelNamePluralLower);
            apiController = apiController.Replace(@"$pkName$", pkName);
            apiController = apiController.Replace(@"$pkDataType$", pkDataType);
            xsfUtils.WriteTextFile(outputPath + @"\Controllers\" + modelNamePlural + "ApiController.cs", apiController);

            // write index
            string index = LoadTemplateByType(TemplateType.View_IndexOrList);

            index = index.Replace(@"$nameSpace$", nameSpace);
            index = index.Replace(@"$nameSpaceRoot$", nameSpaceRoot);
            index = index.Replace(@"$dbContextName$", dbContextName);
            index = index.Replace(@"$modelName$", modelName);
            index = index.Replace(@"$modelNamePlural$", modelNamePlural);
            index = index.Replace(@"$modelNamePluralLower$", modelNamePluralLower);
            index = index.Replace(@"$pkName$", pkName);
            string sortRowItems   = null;
            string filterRowItems = null;
            string dataRowItems   = null;
            string sortRowItem    = @"<th><a href=""#"" onclick=""SortColumn('$modelNamePlural$', '$columnName$', this);""><i class=""fa""></i><span>$columnName$</span></a></th>";
            string filterRowItem  = @"<th><input type=""text"" class=""form-control"" onkeydown=""FilterColumn('$modelNamePlural$', '$columnName$', this, event);"" value="""" /></th>";
            string dataRowItem    = @"<td>@item.$columnName$</td>";
            int    pagerColSpan   = 1;

            foreach (var v in columnNames)
            {
                pagerColSpan += 1;
                string s = sortRowItem.Replace(@"$modelName$", modelName);
                s            = s.Replace(@"$modelNamePlural$", modelNamePlural);
                s            = s.Replace(@"$columnName$", v);
                sortRowItems = sortRowItems + System.Environment.NewLine + s;

                string f = filterRowItem.Replace(@"$modelName$", modelName);
                f = f.Replace(@"$modelNamePlural$", modelNamePlural);
                f = f.Replace(@"$columnName$", v);
                filterRowItems = filterRowItems + System.Environment.NewLine + f;

                string d = dataRowItem.Replace(@"$columnName$", v);
                dataRowItems = dataRowItems + System.Environment.NewLine + d;
            }
            index = index.Replace("{sortRowItems}", sortRowItems);
            index = index.Replace("{filterRowItems}", filterRowItems);
            index = index.Replace("{dataRowItems}", dataRowItems);
            index = index.Replace(@"$pagerColSpan$", pagerColSpan.ToString());

            string edit = LoadTemplateByType(TemplateType.View_CreateOrEdit);

            edit = edit.Replace("$modelName$", modelName);
            edit = edit.Replace("$pkName$", pkName);
            string columns = null;

            foreach (var v in columnNames)
            {
                columns = columns + EditTemplate(v);
            }
            edit = edit.Replace("{columns}", columns);

            xsfUtils.WriteTextFile(outputPath + @"\Views\" + modelNamePlural + @"\Edit.cshtml", edit);
            xsfUtils.WriteTextFile(outputPath + @"\Views\" + modelNamePlural + @"\Index.cshtml", index);
        }
示例#57
0
 // <summary>
 // The constructor for constructing the EntitySet with a given name and an entity type
 // </summary>
 // <param name="name"> The name of the EntitySet </param>
 // <param name="schema"> The db schema </param>
 // <param name="table"> The db table </param>
 // <param name="definingQuery"> The provider specific query that should be used to retrieve the EntitySet </param>
 // <param name="entityType"> The entity type of the entities that this entity set type contains </param>
 // <exception cref="System.ArgumentNullException">Thrown if the argument name or entityType is null</exception>
 internal EntitySet(string name, string schema, string table, string definingQuery, EntityType entityType)
     : base(name, schema, table, definingQuery, entityType)
 {
 }
示例#58
0
        public void WriteAssociationSetMapping_should_write_modification_function_mapping()
        {
            var fixture = new Fixture();

            var entityType = new EntityType("E", "N", DataSpace.CSpace);
            var entitySet  = new EntitySet("ES", "S", null, null, entityType);

            new EntityContainer("EC", DataSpace.SSpace).AddEntitySetBase(entitySet);
            var associationSet = new AssociationSet("AS", new AssociationType("A", XmlConstants.ModelNamespace_3, false, DataSpace.CSpace));

            var associationEndMember1 = new AssociationEndMember("Source", new EntityType("E", "N", DataSpace.CSpace));

            associationSet.AddAssociationSetEnd(new AssociationSetEnd(entitySet, associationSet, associationEndMember1));

            var associationEndMember2 = new AssociationEndMember("Target", new EntityType("E", "N", DataSpace.CSpace));

            associationSet.AddAssociationSetEnd(new AssociationSetEnd(entitySet, associationSet, associationEndMember2));

            var storageModificationFunctionMapping
                = new ModificationFunctionMapping(
                      associationSet,
                      associationSet.ElementType,
                      new EdmFunction("F", "N", DataSpace.SSpace, new EdmFunctionPayload()),
                      new[]
            {
                new ModificationFunctionParameterBinding(
                    new FunctionParameter(
                        "P",
                        TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)),
                        ParameterMode.In),
                    new ModificationFunctionMemberPath(
                        new EdmMember[]
                {
                    new EdmProperty("K"),
                    associationEndMember1
                },
                        associationSet),
                    true),
                new ModificationFunctionParameterBinding(
                    new FunctionParameter(
                        "P",
                        TypeUsage.Create(PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32)),
                        ParameterMode.In),
                    new ModificationFunctionMemberPath(
                        new EdmMember[]
                {
                    new EdmProperty("K"),
                    associationEndMember2
                },
                        associationSet),
                    false)
            },
                      null,
                      null);

            var associationSetMapping
                = new AssociationSetMapping(
                      associationSet,
                      entitySet)
                {
                SourceEndMapping
                    = new EndPropertyMapping
                    {
                    AssociationEnd = associationEndMember1
                    },
                TargetEndMapping
                    = new EndPropertyMapping
                    {
                    AssociationEnd = associationEndMember2
                    },
                ModificationFunctionMapping = new AssociationSetModificationFunctionMapping(
                    associationSet,
                    storageModificationFunctionMapping,
                    storageModificationFunctionMapping)
                };

            fixture.Writer.WriteAssociationSetMappingElement(associationSetMapping);

            Assert.Equal(
                @"<AssociationSetMapping Name=""AS"" TypeName="".A"" StoreEntitySet=""E"">
  <EndProperty Name=""Source"" />
  <EndProperty Name=""Target"" />
  <ModificationFunctionMapping>
    <InsertFunction FunctionName=""N.F"">
      <EndProperty Name=""Source"">
        <ScalarProperty Name=""K"" ParameterName=""P"" Version=""Current"" />
      </EndProperty>
      <EndProperty Name=""Target"">
        <ScalarProperty Name=""K"" ParameterName=""P"" Version=""Original"" />
      </EndProperty>
    </InsertFunction>
    <DeleteFunction FunctionName=""N.F"">
      <EndProperty Name=""Source"">
        <ScalarProperty Name=""K"" ParameterName=""P"" Version=""Current"" />
      </EndProperty>
      <EndProperty Name=""Target"">
        <ScalarProperty Name=""K"" ParameterName=""P"" Version=""Original"" />
      </EndProperty>
    </DeleteFunction>
  </ModificationFunctionMapping>
</AssociationSetMapping>",
                fixture.ToString());
        }
示例#59
0
 public static EntitySet GetEntitySet(this EdmModel model, System.Data.Entity.Core.Metadata.Edm.EntityType entityType)
 {
     return(model.GetEntitySets().SingleOrDefault <EntitySet>((Func <EntitySet, bool>)(e => e.ElementType == entityType.GetRootType())));
 }
        public void Create_checks_each_EntitySet_parameter_against_corresponding_AssociationEndMember()
        {
            var source    = new EntityType("Source", "Namespace", DataSpace.CSpace);
            var target    = new EntityType("Target", "Namespace", DataSpace.CSpace);
            var other     = new EntityType("Other", "Namespace", DataSpace.CSpace);
            var sourceSet = new EntitySet("SourceSet", "Schema", "Table", "Query", source);
            var targetSet = new EntitySet("TargetSet", "Schema", "Table", "Query", target);
            var otherSet  = new EntitySet("OtherSet", "Schema", "Table", "Query", other);
            var sourceEnd = new AssociationEndMember("SourceEnd", source);
            var targetEnd = new AssociationEndMember("TargetEnd", target);

            var associationTypeWithNonNullEndMembers =
                AssociationType.Create(
                    "AssociationType",
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    sourceEnd,
                    targetEnd,
                    null,
                    null);

            var associationTypeWithNullEndMembers =
                AssociationType.Create(
                    "AssociationType",
                    "Namespace",
                    true,
                    DataSpace.CSpace,
                    null, // sourceEnd
                    null, // targetEnd
                    null,
                    null);

            Assert.NotNull(
                AssociationSet.Create(
                    "AssociationSet",
                    associationTypeWithNonNullEndMembers,
                    sourceSet,
                    targetSet,
                    null));

            Assert.NotNull(
                AssociationSet.Create(
                    "AssociationSet",
                    associationTypeWithNullEndMembers,
                    null, // sourceSet
                    null, // targetSet
                    null));

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        otherSet,
                        targetSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        sourceSet,
                        otherSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        null, // sourceSet
                        targetSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNonNullEndMembers,
                        sourceSet,
                        null, // targetSet
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNullEndMembers,
                        null, // sourceSet
                        targetSet,
                        null)).Message);

            Assert.Equal(
                Resources.Strings.AssociationSet_EndEntityTypeMismatch,
                Assert.Throws <ArgumentException>(
                    () => AssociationSet.Create(
                        "AssociationSet",
                        associationTypeWithNullEndMembers,
                        sourceSet,
                        null, // targetSet
                        null)).Message);
        }