public override void Apply(IEntityTypeConfiguration entity, ODataModelBuilder model)
 {
     if (entity.IsAbstract == null)
     {
         entity.IsAbstract = entity.ClrType.IsAbstract;
     }
 }
Exemplo n.º 2
0
 public static ICodeFirst ApplyConfiguration <TEntity>(this ICodeFirst codeFirst, IEntityTypeConfiguration <TEntity> configuration) where TEntity : class
 {
     return(codeFirst.Entity <TEntity>(eb =>
     {
         configuration.Configure(eb);
     }));
 }
        /// <summary>
        /// Sets the base type of this entity type.
        /// </summary>
        /// <param name="baseType">The base entity type.</param>
        /// <returns>Returns itself so that multiple calls can be chained.</returns>
        public IEntityTypeConfiguration DerivesFrom(IEntityTypeConfiguration baseType)
        {
            if (baseType == null)
            {
                throw Error.ArgumentNull("baseType");
            }

            _baseType           = baseType;
            _baseTypeConfigured = true;

            if (!baseType.ClrType.IsAssignableFrom(ClrType) || baseType.ClrType == ClrType)
            {
                throw Error.InvalidOperation(SRResources.TypeDoesNotInheritFromBaseType, ClrType.FullName, baseType.ClrType.FullName);
            }

            if (Keys.Any())
            {
                throw Error.InvalidOperation(SRResources.CannotDefineKeysOnDerivedTypes, FullName, baseType.FullName);
            }

            foreach (PropertyConfiguration property in Properties)
            {
                ValidatePropertyNotAlreadyDefinedInBaseTypes(property.PropertyInfo);
            }

            foreach (PropertyConfiguration property in this.DerivedProperties())
            {
                ValidatePropertyNotAlreadyDefinedInDerivedTypes(property.PropertyInfo);
            }

            return(this);
        }
Exemplo n.º 4
0
        public void CanCreateActionWithEntityReturnType()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();

            ActionConfiguration createGoodCustomer = new ActionConfiguration(builder, "CreateGoodCustomer");

            createGoodCustomer.ReturnsFromEntitySet <Customer>("GoodCustomers");

            ActionConfiguration createBadCustomers = new ActionConfiguration(builder, "CreateBadCustomers");

            createBadCustomers.ReturnsCollectionFromEntitySet <Customer>("BadCustomers");

            // Assert
            IEntityTypeConfiguration customer = createGoodCustomer.ReturnType as IEntityTypeConfiguration;

            Assert.NotNull(customer);
            Assert.Equal(typeof(Customer).FullName, customer.FullName);
            IEntitySetConfiguration goodCustomers = builder.EntitySets.SingleOrDefault(s => s.Name == "GoodCustomers");

            Assert.NotNull(goodCustomers);
            Assert.Same(createGoodCustomer.EntitySet, goodCustomers);

            ICollectionTypeConfiguration customers = createBadCustomers.ReturnType as ICollectionTypeConfiguration;

            Assert.NotNull(customers);
            customer = customers.ElementType as IEntityTypeConfiguration;
            Assert.NotNull(customer);
            IEntitySetConfiguration badCustomers = builder.EntitySets.SingleOrDefault(s => s.Name == "BadCustomers");

            Assert.NotNull(badCustomers);
            Assert.Same(createBadCustomers.EntitySet, badCustomers);
        }
        internal void MapDerivedTypes(IEntityTypeConfiguration entity)
        {
            HashSet <Type> visitedEntities = new HashSet <Type>();

            Queue <IEntityTypeConfiguration> entitiesToBeVisited = new Queue <IEntityTypeConfiguration>();

            entitiesToBeVisited.Enqueue(entity);

            // populate all the derived types
            while (entitiesToBeVisited.Count != 0)
            {
                IEntityTypeConfiguration baseEntity = entitiesToBeVisited.Dequeue();
                visitedEntities.Add(baseEntity.ClrType);

                List <Type> derivedTypes;
                if (_allTypesWithDerivedTypeMapping.Value.TryGetValue(baseEntity.ClrType, out derivedTypes))
                {
                    foreach (Type derivedType in derivedTypes)
                    {
                        if (!visitedEntities.Contains(derivedType) && !IsIgnoredType(derivedType))
                        {
                            IEntityTypeConfiguration derivedEntity = AddEntity(derivedType);
                            entitiesToBeVisited.Enqueue(derivedEntity);
                        }
                    }
                }
            }
        }
        public void AssociationSetDiscoveryConvention_AddsBindingForBaseAndDerivedNavigationProperties()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            IEntityTypeConfiguration vehicle = builder.AddEntity(typeof(Vehicle));

            IEntityTypeConfiguration        car = builder.AddEntity(typeof(Car)).DerivesFrom(vehicle);
            NavigationPropertyConfiguration carNavigationProperty = car.AddNavigationProperty(typeof(Car).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            IEntityTypeConfiguration        motorcycle = builder.AddEntity(typeof(Motorcycle)).DerivesFrom(vehicle);
            NavigationPropertyConfiguration motorcycleNavigationProperty = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            IEntityTypeConfiguration manufacturer           = builder.AddEntity(typeof(Manufacturer));
            IEntityTypeConfiguration motorcycleManufacturer = builder.AddEntity(typeof(MotorcycleManufacturer)).DerivesFrom(manufacturer);
            IEntityTypeConfiguration carManufacturer        = builder.AddEntity(typeof(CarManufacturer)).DerivesFrom(manufacturer);

            IEntitySetConfiguration manufacturers = builder.AddEntitySet("manufacturers", manufacturer);


            Mock <IEntitySetConfiguration> entitySet = new Mock <IEntitySetConfiguration>(MockBehavior.Strict);

            entitySet.Setup(v => v.EntityType).Returns(vehicle);
            entitySet.Setup(v => v.AddBinding(motorcycleNavigationProperty, manufacturers)).Returns <NavigationPropertyConfiguration>(null);
            entitySet.Setup(v => v.AddBinding(carNavigationProperty, manufacturers)).Returns <NavigationPropertyConfiguration>(null);

            // Act
            _convention.Apply(entitySet.Object, builder);

            // Assert
            entitySet.VerifyAll();
        }
        /// <summary>
        /// Registers an entity set as a part of the model and returns an object that can be used to configure the entity set.
        /// This method can be called multiple times for the same type to perform multiple lines of configuration.
        /// </summary>
        /// <param name="name">The name of the entity set.</param>
        /// <param name="entityType">The type to be registered or configured.</param>
        /// <returns>The configuration object for the specified entity set.</returns>
        public virtual IEntitySetConfiguration AddEntitySet(string name, IEntityTypeConfiguration entityType)
        {
            if (String.IsNullOrWhiteSpace(name))
            {
                throw Error.ArgumentNullOrEmpty("name");
            }

            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }

            if (name.Contains("."))
            {
                throw Error.NotSupported(SRResources.InvalidEntitySetName, name);
            }

            EntitySetConfiguration entitySet = null;
            if (_entitySets.ContainsKey(name))
            {
                entitySet = _entitySets[name] as EntitySetConfiguration;
                if (entitySet.EntityType != entityType)
                {
                    throw Error.Argument("entityType", SRResources.EntitySetAlreadyConfiguredDifferentEntityType, entitySet.Name, entitySet.EntityType.Name);
                }
            }
            else
            {
                entitySet = new EntitySetConfiguration(this, entityType, name);
                _entitySets[name] = entitySet;
            }
            return entitySet;
        }
Exemplo n.º 8
0
        private void CreateEdmTypeHeader(IStructuralTypeConfiguration config)
        {
            if (!_types.ContainsKey(config.ClrType))
            {
                if (config.Kind == EdmTypeKind.Complex)
                {
                    _types.Add(config.ClrType, new EdmComplexType(config.Namespace, config.Name));
                }
                else
                {
                    IEntityTypeConfiguration entity = config as IEntityTypeConfiguration;
                    Contract.Assert(entity != null);

                    IEdmEntityType baseType = null;

                    if (entity.BaseType != null)
                    {
                        CreateEdmTypeHeader(entity.BaseType);
                        baseType = _types[entity.BaseType.ClrType] as IEdmEntityType;

                        Contract.Assert(baseType != null);
                    }

                    _types.Add(config.ClrType, new EdmEntityType(config.Namespace, config.Name, baseType, entity.IsAbstract ?? false, isOpen: false));
                }
            }
        }
        private void MapEntityType(IEntityTypeConfiguration entity)
        {
            IEnumerable <PropertyInfo> properties = ConventionsHelpers.GetProperties(entity);

            foreach (PropertyInfo property in properties)
            {
                bool isCollection;
                IStructuralTypeConfiguration mappedType;

                PropertyKind propertyKind = GetPropertyType(property, out isCollection, out mappedType);

                if (propertyKind == PropertyKind.Primitive || propertyKind == PropertyKind.Complex)
                {
                    MapStructuralProperty(entity, property, propertyKind, isCollection);
                }
                else
                {
                    // don't add this property if the user has already added it.
                    if (!entity.NavigationProperties.Where(p => p.Name == property.Name).Any())
                    {
                        if (!isCollection)
                        {
                            entity.AddNavigationProperty(property, EdmMultiplicity.ZeroOrOne);
                        }
                        else
                        {
                            entity.AddNavigationProperty(property, EdmMultiplicity.Many);
                        }
                    }
                }
            }

            MapDerivedTypes(entity);
        }
Exemplo n.º 10
0
        private void MapEntityType(IEntityTypeConfiguration entity)
        {
            PropertyInfo[] properties = ConventionsHelpers.GetProperties(entity);
            foreach (PropertyInfo property in properties)
            {
                bool isCollection;
                IStructuralTypeConfiguration mappedType;

                PropertyKind propertyKind = GetPropertyType(property, out isCollection, out mappedType);

                if (propertyKind == PropertyKind.Primitive || propertyKind == PropertyKind.Complex)
                {
                    MapStructuralProperty(entity, property, propertyKind, isCollection);
                }
                else
                {
                    if (!isCollection)
                    {
                        entity.AddNavigationProperty(property, EdmMultiplicity.ZeroOrOne);
                    }
                    else
                    {
                        entity.AddNavigationProperty(property, EdmMultiplicity.Many);
                    }
                }
            }
        }
Exemplo n.º 11
0
        public void ThisAndBaseTypes_ReturnsThisType()
        {
            ODataModelBuilder        builder   = GetMockVehicleModel();
            IEntityTypeConfiguration sportbike = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "sportbike").Single();

            Assert.Contains(sportbike, sportbike.ThisAndBaseTypes());
        }
 private void MapEntityType(IEntityTypeConfiguration entity)
 {
     PropertyInfo[] properties = ConventionsHelpers.GetProperties(entity.ClrType);
     foreach (PropertyInfo property in properties)
     {
         if (EdmLibHelpers.GetEdmPrimitiveTypeOrNull(property.PropertyType) != null)
         {
             PrimitivePropertyConfiguration primitiveProperty = entity.AddProperty(property);
             primitiveProperty.OptionalProperty = IsNullable(property.PropertyType);
         }
         else
         {
             IStructuralTypeConfiguration mappedType = GetStructuralTypeOrNull(property.PropertyType);
             if (mappedType != null)
             {
                 if (mappedType is IComplexTypeConfiguration)
                 {
                     entity.AddComplexProperty(property);
                 }
                 else
                 {
                     entity.AddNavigationProperty(property, property.PropertyType.IsCollection() ? EdmMultiplicity.Many : EdmMultiplicity.ZeroOrOne);
                 }
             }
             else
             {
                 // we are not really sure if this should be a complex property or an navigation property.
                 // Assume that it is a navigation property and patch later in RediscoverComplexTypes().
                 entity.AddNavigationProperty(property, property.PropertyType.IsCollection() ? EdmMultiplicity.Many : EdmMultiplicity.ZeroOrOne);
             }
         }
     }
 }
Exemplo n.º 13
0
        private void Configure <TModel, TModelConfig>(ModelBuilder modelBuilder)
            where TModel : class
            where TModelConfig : IEntityTypeConfiguration <TModel>
        {
            IEntityTypeConfiguration <TModel> configuration = Activator.CreateInstance <TModelConfig>();

            modelBuilder.ApplyConfiguration(configuration);
        }
Exemplo n.º 14
0
        private void Configure <TEntity, TEntityConfig>(ModelBuilder builder)
            where TEntity : class
            where TEntityConfig : IEntityTypeConfiguration <TEntity>
        {
            IEntityTypeConfiguration <TEntity> configuration = Activator.CreateInstance <TEntityConfig>();

            builder.ApplyConfiguration(configuration);
        }
Exemplo n.º 15
0
        public static void AddType <TEntity>(IEntityTypeConfiguration <TEntity> configuration) where TEntity : class
        {
            var builder = new EntityTypeBuilder <TEntity>();

            configuration.Configure(builder);

            AnalyzeType(typeof(TEntity));
        }
Exemplo n.º 16
0
        public void CanBuildBoundProcedureCacheForIEdmModel()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;

            customer.HasKey(c => c.ID);
            customer.Property(c => c.Name);
            customer.ComplexProperty(c => c.Address);

            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;

            movie.HasKey(m => m.ID);
            movie.HasKey(m => m.Name);
            EntityTypeConfiguration <Blockbuster> blockBuster = builder.Entity <Blockbuster>().DerivesFrom <Movie>();
            IEntityTypeConfiguration movieConfiguration       = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Single(t => t.Name == "Movie");

            // build actions that are bindable to a single entity
            customer.Action("InCache1_CustomerAction");
            customer.Action("InCache2_CustomerAction");
            movie.Action("InCache3_MovieAction");
            ActionConfiguration incache4_MovieAction = new ActionConfiguration(builder, "InCache4_MovieAction");

            incache4_MovieAction.SetBindingParameter("bindingParameter", movieConfiguration, true);
            blockBuster.Action("InCache5_BlockbusterAction");

            // build actions that are either: bindable to a collection of entities, have no parameter, have only complex parameter
            customer.Collection.Action("NotInCache1_CustomersAction");
            movie.Collection.Action("NotInCache2_MoviesAction");
            ActionConfiguration notInCache3_NoParameters     = new ActionConfiguration(builder, "NotInCache3_NoParameters");
            ActionConfiguration notInCache4_AddressParameter = new ActionConfiguration(builder, "NotInCache4_AddressParameter");

            notInCache4_AddressParameter.Parameter <Address>("address");

            IEdmModel      model           = builder.GetEdmModel();
            IEdmEntityType customerType    = model.SchemaElements.OfType <IEdmEntityType>().Single(e => e.Name == "Customer");
            IEdmEntityType movieType       = model.SchemaElements.OfType <IEdmEntityType>().Single(e => e.Name == "Movie");
            IEdmEntityType blockBusterType = model.SchemaElements.OfType <IEdmEntityType>().Single(e => e.Name == "Blockbuster");

            // Act
            BindableProcedureFinder annotation = new BindableProcedureFinder(model);

            IEdmFunctionImport[] movieActions       = annotation.FindProcedures(movieType).ToArray();
            IEdmFunctionImport[] customerActions    = annotation.FindProcedures(customerType).ToArray();
            IEdmFunctionImport[] blockBusterActions = annotation.FindProcedures(blockBusterType).ToArray();

            // Assert
            Assert.Equal(2, customerActions.Length);
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache1_CustomerAction"));
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache2_CustomerAction"));
            Assert.Equal(2, movieActions.Length);
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.Equal(3, blockBusterActions.Length);
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache5_BlockbusterAction"));
        }
        public void Apply(IEdmTypeConfiguration edmTypeConfiguration, ODataModelBuilder model)
        {
            IEntityTypeConfiguration entity = edmTypeConfiguration as IEntityTypeConfiguration;

            if (entity != null)
            {
                Apply(entity, model);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        ///     Applies configuration that is defined in an <see cref="IEntityTypeConfiguration{TEntity}" /> instance.
        /// </summary>
        /// <typeparam name="TEntity"> The entity type to be configured. </typeparam>
        /// <param name="configuration"> The configuration to be applied. </param>
        /// <returns>
        ///     The same <see cref="ModelBuilder" /> instance so that additional configuration calls can be chained.
        /// </returns>
        public virtual ModelBuilder ApplyConfiguration <TEntity>([NotNull] IEntityTypeConfiguration <TEntity> configuration)
            where TEntity : class
        {
            Check.NotNull(configuration, nameof(configuration));

            configuration.Configure(Entity <TEntity>());

            return(this);
        }
        // Returns the base types, this type and all the derived types of this type.
        public static IEnumerable<IEntityTypeConfiguration> ThisAndBaseAndDerivedTypes(this ODataModelBuilder modelBuilder, IEntityTypeConfiguration entity)
        {
            Contract.Assert(modelBuilder != null);
            Contract.Assert(entity != null);

            return entity.BaseTypes()
                    .Concat(new[] { entity })
                    .Concat(modelBuilder.DerivedTypes(entity));
        }
Exemplo n.º 20
0
        public void ThisAndBaseAndDerivedTypes_Works()
        {
            ODataModelBuilder        builder = GetMockVehicleModel();
            IEntityTypeConfiguration vehicle = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "vehicle").Single();

            Assert.Equal(
                builder.ThisAndBaseAndDerivedTypes(vehicle).Select(e => e.Name).OrderBy(name => name),
                builder.StructuralTypes.Select(e => e.Name).OrderBy(name => name));
        }
Exemplo n.º 21
0
        internal EntityTypeConfiguration(ODataModelBuilder modelBuilder, IEntityTypeConfiguration configuration)
            : base(configuration)
        {
            Contract.Assert(modelBuilder != null);
            Contract.Assert(configuration != null);

            _modelBuilder  = modelBuilder;
            _configuration = configuration;
            _collection    = new EntityCollectionConfiguration <TEntityType>(configuration);
        }
Exemplo n.º 22
0
        public ModelBuilder ApplyConfiguration <TEntity>(IEntityTypeConfiguration <TEntity> entityTypeConfiguration) where TEntity : class
        {
            if (entityTypeConfiguration is null)
            {
                throw new ArgumentNullException(nameof(entityTypeConfiguration));
            }

            entityTypeConfiguration.Configure(Entity <TEntity>());

            return(this);
        }
        public override IEntityTypeConfiguration AddEntity(Type type)
        {
            IEntityTypeConfiguration entityTypeConfiguration = base.AddEntity(type);

            if (_isModelBeingBuilt)
            {
                MapType(entityTypeConfiguration);
            }

            return(entityTypeConfiguration);
        }
        public override IEntitySetConfiguration AddEntitySet(string name, IEntityTypeConfiguration entityType)
        {
            IEntitySetConfiguration entitySetConfiguration = base.AddEntitySet(name, entityType);

            if (_isModelBeingBuilt)
            {
                ApplyEntitySetConventions(entitySetConfiguration);
            }

            return(entitySetConfiguration);
        }
Exemplo n.º 25
0
        private static void ApplyConfiguration <T>(this ModelBuilder modelBuilder,
                                                   IEntityTypeConfiguration <T> configuration) where T : class
        {
            Type entityType = FindEntityType(configuration.GetType());

            dynamic entityTypeBuilder = EntityMethod
                                        .MakeGenericMethod(entityType)
                                        .Invoke(modelBuilder, new object[0]);

            configuration.Configure(entityTypeBuilder);
        }
        internal EntitySetConfiguration(ODataModelBuilder modelBuilder, IEntityTypeConfiguration entityType, string name)
        {
            _modelBuilder = modelBuilder;
            Name = name;
            EntityType = entityType;
            ClrType = entityType.ClrType;
            _url = Name;

            _editLinkFactory = null;
            _readLinkFactory = null;
            _navigationPropertyLinkBuilders = new Dictionary<string, Func<EntityInstanceContext, IEdmNavigationProperty, Uri>>();
        }
Exemplo n.º 27
0
        public void DerivedTypes_Works()
        {
            ODataModelBuilder        builder    = GetMockVehicleModel();
            IEntityTypeConfiguration vehicle    = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "vehicle").Single();
            IEntityTypeConfiguration car        = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "car").Single();
            IEntityTypeConfiguration motorcycle = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "motorcycle").Single();
            IEntityTypeConfiguration sportbike  = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "sportbike").Single();

            Assert.Equal(
                builder.DerivedTypes(vehicle).Select(e => e.Name).OrderBy(name => name),
                new[] { sportbike, motorcycle, car }.Select(e => e.Name).OrderBy(name => name));
        }
        internal EntitySetConfiguration(ODataModelBuilder modelBuilder, IEntityTypeConfiguration entityType, string name)
        {
            _modelBuilder = modelBuilder;
            Name          = name;
            EntityType    = entityType;
            ClrType       = entityType.ClrType;
            _url          = Name;

            _editLinkFactory = null;
            _readLinkFactory = null;
            _navigationPropertyLinkBuilders = new Dictionary <NavigationPropertyConfiguration, Func <EntityInstanceContext, IEdmNavigationProperty, Uri> >();
        }
Exemplo n.º 29
0
        public void IsAssignableFrom_ReturnsFalseForBaseType()
        {
            ODataModelBuilder        builder    = GetMockVehicleModel();
            IEntityTypeConfiguration vehicle    = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "vehicle").Single();
            IEntityTypeConfiguration car        = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "car").Single();
            IEntityTypeConfiguration motorcycle = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "motorcycle").Single();
            IEntityTypeConfiguration sportbike  = builder.StructuralTypes.OfType <IEntityTypeConfiguration>().Where(e => e.Name == "sportbike").Single();

            Assert.False(car.IsAssignableFrom(vehicle));
            Assert.False(motorcycle.IsAssignableFrom(vehicle));
            Assert.False(sportbike.IsAssignableFrom(vehicle));
        }
Exemplo n.º 30
0
        // Returns the base types for this type.
        public static IEnumerable <IEntityTypeConfiguration> BaseTypes(this IEntityTypeConfiguration entity)
        {
            Contract.Assert(entity != null);

            entity = entity.BaseType;
            while (entity != null)
            {
                yield return(entity);

                entity = entity.BaseType;
            }
        }
Exemplo n.º 31
0
        public static bool IsAssignableFrom(this IEntityTypeConfiguration baseEntity, IEntityTypeConfiguration entity)
        {
            while (entity != null)
            {
                if (baseEntity == entity)
                {
                    return(true);
                }
                entity = entity.BaseType;
            }

            return(false);
        }
        public void GetTargetEntitySet_Returns_Null_IfNoMatchingTargetEntitySet()
        {
            // Arrange
            ODataModelBuilder               builder            = new ODataModelBuilder();
            IEntityTypeConfiguration        motorcycle         = builder.AddEntity(typeof(Motorcycle));
            NavigationPropertyConfiguration navigationProperty = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            // Act
            IEntitySetConfiguration targetEntitySet = AssociationSetDiscoveryConvention.GetTargetEntitySet(navigationProperty, builder);

            // Assert
            Assert.Null(targetEntitySet);
        }
        public override void Apply(IEntityTypeConfiguration entity, ODataModelBuilder model)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }

            PropertyInfo key = ConventionsHelpers.GetKeyProperty(entity.ClrType);
            if (key != null)
            {
                entity.HasKey(key);
            }
        }
        private static PropertyConfiguration GetKeyProperty(IEntityTypeConfiguration entityType)
        {
            IEnumerable<PropertyConfiguration> keys =
                entityType.Properties
                .Where(p => (p.Name.Equals(entityType.Name + "Id", StringComparison.OrdinalIgnoreCase) || p.Name.Equals("Id", StringComparison.OrdinalIgnoreCase))
                && EdmLibHelpers.GetEdmPrimitiveTypeOrNull(p.PropertyInfo.PropertyType) != null);

            if (keys.Count() == 1)
            {
                return keys.Single();
            }

            return null;
        }
 public static string GetEntityKeyValue(EntityInstanceContext entityContext, IEntityTypeConfiguration entityTypeConfiguration)
 {
     // TODO: BUG 453795: reflection cleanup
     if (entityTypeConfiguration.Keys.Count() == 1)
     {
         return GetUriRepresentationForKeyValue(entityTypeConfiguration.Keys.First().PropertyInfo, entityContext.EntityInstance);
     }
     else
     {
         return String.Join(
             ",",
             entityTypeConfiguration
                 .Keys
                 .Select(
                     key => String.Format(CultureInfo.InvariantCulture, "{0}={1}", key.Name, GetUriRepresentationForKeyValue(key.PropertyInfo, entityContext.EntityInstance))));
     }
 }
        /// <summary>
        /// Figures out the key properties and marks them as Keys in the EDM model.
        /// </summary>
        /// <param name="entity">The entity type being configured.</param>
        /// <param name="model">The <see cref="ODataModelBuilder"/>.</param>
        public override void Apply(IEntityTypeConfiguration entity, ODataModelBuilder model)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }

            // Try to figure out keys only if there is no base type.
            if (entity.BaseType == null)
            {
                PropertyConfiguration key = GetKeyProperty(entity);
                if (key != null)
                {
                    entity.HasKey(key.PropertyInfo);
                }
            }
        }
        public NavigationPropertyConfiguration(PropertyInfo property, EdmMultiplicity multiplicity, IEntityTypeConfiguration declaringType)
            : base(property, declaringType)
        {
            if (property == null)
            {
                throw Error.ArgumentNull("property");
            }

            Multiplicity = multiplicity;

            _relatedType = property.PropertyType;
            if (multiplicity == EdmMultiplicity.Many)
            {
                Type elementType;
                if (!_relatedType.IsCollection(out elementType))
                {
                    throw Error.InvalidOperation(SRResources.ManyToManyNavigationPropertyMustReturnCollection, property.Name, property.ReflectedType.Name);
                }

                _relatedType = elementType;
            }
        }
        // Returns all the derived types of this type.
        public static IEnumerable<IEntityTypeConfiguration> DerivedTypes(this ODataModelBuilder modelBuilder, IEntityTypeConfiguration entity)
        {
            if (modelBuilder == null)
            {
                throw Error.ArgumentNull("modelBuilder");
            }

            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }

            IEnumerable<IEntityTypeConfiguration> derivedEntities = modelBuilder.StructuralTypes.OfType<IEntityTypeConfiguration>().Where(e => e.BaseType == entity);

            foreach (IEntityTypeConfiguration derivedEntity in derivedEntities)
            {
                yield return derivedEntity;
                foreach (IEntityTypeConfiguration derivedDerivedEntity in modelBuilder.DerivedTypes(derivedEntity))
                {
                    yield return derivedDerivedEntity;
                }
            }
        }
        private static IEntitySetConfiguration GetDefaultEntitySet(IEntityTypeConfiguration targetEntityType, ODataModelBuilder model)
        {
            if (targetEntityType == null)
            {
                return null;
            }

            IEnumerable<IEntitySetConfiguration> matchingEntitySets = model.EntitySets.Where(e => e.EntityType == targetEntityType);

            if (matchingEntitySets.Count() > 1)
            {
                // no default entity set if more than one entity set match.
                return null;
            }
            else if (matchingEntitySets.Count() == 1)
            {
                return matchingEntitySets.Single();
            }
            else
            {
                // default entity set is the same as the default entity set for the base type.
                return GetDefaultEntitySet(targetEntityType.BaseType, model);
            }
        }
 /// <summary>
 /// Sets the base type of this entity type to <c>null</c> meaning that this entity type 
 /// does not derive from anything.
 /// </summary>
 /// <returns>Returns itself so that multiple calls can be chained.</returns>
 public IEntityTypeConfiguration DerivesFromNothing()
 {
     _baseType = null;
     _baseTypeConfigured = true;
     return this;
 }
        private void MapEntityType(IEntityTypeConfiguration entity)
        {
            PropertyInfo[] properties = ConventionsHelpers.GetProperties(entity);
            foreach (PropertyInfo property in properties)
            {
                bool isCollection;
                IStructuralTypeConfiguration mappedType;

                PropertyKind propertyKind = GetPropertyType(property, out isCollection, out mappedType);

                if (propertyKind == PropertyKind.Primitive || propertyKind == PropertyKind.Complex)
                {
                    MapStructuralProperty(entity, property, propertyKind, isCollection);
                }
                else
                {
                    if (!isCollection)
                    {
                        entity.AddNavigationProperty(property, EdmMultiplicity.ZeroOrOne);
                    }
                    else
                    {
                        entity.AddNavigationProperty(property, EdmMultiplicity.Many);
                    }
                }
            }
        }
 /// <summary>
 /// Applies the convention.
 /// </summary>
 /// <param name="entity">The <see cref="IEntityTypeConfiguration"/> to apply the convention on.</param>
 /// <param name="model">The <see cref="ODataModelBuilder"/> instance.</param>
 public abstract void Apply(IEntityTypeConfiguration entity, ODataModelBuilder model);
        public override IEntitySetConfiguration AddEntitySet(string name, IEntityTypeConfiguration entityType)
        {
            IEntitySetConfiguration entitySetConfiguration = base.AddEntitySet(name, entityType);
            if (_isModelBeingBuilt)
            {
                ApplyEntitySetConventions(entitySetConfiguration);
            }

            return entitySetConfiguration;
        }
        /// <summary>
        /// Sets the base type of this entity type.
        /// </summary>
        /// <param name="baseType">The base entity type.</param>
        /// <returns>Returns itself so that multiple calls can be chained.</returns>
        public IEntityTypeConfiguration DerivesFrom(IEntityTypeConfiguration baseType)
        {
            if (baseType == null)
            {
                throw Error.ArgumentNull("baseType");
            }

            if (!baseType.ClrType.IsAssignableFrom(ClrType) || baseType.ClrType == ClrType)
            {
                throw Error.InvalidOperation(SRResources.TypeDoesNotInheritFromBaseType, ClrType.FullName, baseType.ClrType.FullName);
            }

            if (Keys.Any())
            {
                throw Error.InvalidOperation(SRResources.CannotDefineKeysOnDerivedTypes, FullName, baseType.FullName);
            }

            _baseType = baseType;

            foreach (PropertyConfiguration property in Properties)
            {
                ValidatePropertyNotAlreadyDefinedInBaseTypes(property.PropertyInfo);
            }

            foreach (PropertyConfiguration property in this.DerivedProperties())
            {
                ValidatePropertyNotAlreadyDefinedInDerivedTypes(property.PropertyInfo);
            }

            return this;
        }
Exemplo n.º 45
0
        private void CreateEntityTypeBody(EdmEntityType type, IEntityTypeConfiguration config)
        {
            CreateStructuralTypeBody(type, config);
            IEdmStructuralProperty[] keys = config.Keys.Select(p => type.DeclaredProperties.OfType<IEdmStructuralProperty>().First(dp => dp.Name == p.PropertyInfo.Name)).ToArray();
            type.AddKeys(keys);

            foreach (NavigationPropertyConfiguration navProp in config.NavigationProperties)
            {
                EdmNavigationPropertyInfo info = new EdmNavigationPropertyInfo();
                info.Name = navProp.Name;
                info.TargetMultiplicity = navProp.Multiplicity;
                info.Target = _types[navProp.RelatedClrType] as IEdmEntityType;
                //TODO: If target end has a multiplity of 1 this assumes the source end is 0..1.
                //      I think a better default multiplicity is *
                type.AddUnidirectionalNavigation(info);
            }
        }
        public static bool IsAssignableFrom(this IEntityTypeConfiguration baseEntity, IEntityTypeConfiguration entity)
        {
            while (entity != null)
            {
                if (baseEntity == entity)
                {
                    return true;
                }
                entity = entity.BaseType;
            }

            return false;
        }