コード例 #1
0
        /// <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(EntityTypeConfiguration entity, ODataConventionModelBuilder model)
        {
            if (entity == null)
            {
                throw Error.ArgumentNull("entity");
            }

            // Suppress the EntityKeyConvention if there is any key in EntityTypeConfiguration.
            if (entity.Keys.Any() || entity.EnumKeys.Any())
            {
                return;
            }

            // Suppress the EntityKeyConvention if base type has any key.
            if (entity.BaseType != null && entity.BaseType.Keys().Any())
            {
                return;
            }

            PropertyConfiguration key = GetKeyProperty(entity);
            if (key != null)
            {
                entity.HasKey(key.PropertyInfo);
            }
        }
コード例 #2
0
 public NhsContext(EntityTypeConfiguration<Person> personTypeConfiguration,
     EntityTypeConfiguration<Colour> colourTypeConfiguration)
     : base("name=NhsContext")
 {
     _personTypeConfiguration = personTypeConfiguration;
     _colourTypeConfiguration = colourTypeConfiguration;
 }
コード例 #3
0
ファイル: UserMap.cs プロジェクト: EricOrYhj/PinEveryThing
 public void RegTo(ConfigurationRegistrar confRegistrar)
 {
     var r = new EntityTypeConfiguration<UserInfo>();
     r.ToTable("UserInfo");
     r.HasKey(p => p.AutoId);
     confRegistrar.Add<UserInfo>(r);
 }
コード例 #4
0
 public override void Apply(EntityTypeConfiguration entity, ODataModelBuilder model)
 {
     if (entity.IsAbstract == null)
     {
         entity.IsAbstract = entity.ClrType.IsAbstract;
     }
 }
コード例 #5
0
        public void Can_get_and_set_table_name()
        {
            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object));
            entityTypeConfiguration.ToTable("Foo");

            Assert.Equal("Foo", entityTypeConfiguration.GetTableName().Name);
        }
コード例 #6
0
        private static NavigationSourceConfiguration GetDefaultNavigationSource(EntityTypeConfiguration targetEntityType,
            ODataModelBuilder model, bool isSingleton)
        {
            if (targetEntityType == null)
            {
                return null;
            }

            NavigationSourceConfiguration[] matchingNavigationSources = null;
            if (isSingleton)
            {
                matchingNavigationSources = model.Singletons.Where(e => e.EntityType == targetEntityType).ToArray();
            }
            else
            {
                matchingNavigationSources = model.EntitySets.Where(e => e.EntityType == targetEntityType).ToArray();
            }

            if (matchingNavigationSources.Length > 1)
            {
                return null;
            }
            else if (matchingNavigationSources.Length == 1)
            {
                return matchingNavigationSources[0];
            }
            else
            {
                // default navigation source is the same as the default navigation source for the base type.
                return GetDefaultNavigationSource(targetEntityType.BaseType as EntityTypeConfiguration,
                    model, isSingleton);
            }
        }
        /// <summary>
        ///     Constructor.
        /// </summary>
        /// <param name="nameChanges"></param>
        internal ExpressionTranslator(EntityTypeConfiguration configuration)
        {
            //_nameChanges = nameChanges;
            _configuration = configuration;
            _nameChanges = configuration.KeyMappings;

            _constantEvaluator = new ExpressionEvaluator();
        }
コード例 #8
0
 /// <summary>Defines the mapping information for the entity 'ApiDataSource'</summary>
 /// <param name="config">The configuration to modify.</param>
 protected virtual void MapApiDataSource(EntityTypeConfiguration<ApiDataSource> config)
 {
     config.ToTable("ApiDataSource");
     config.HasKey(t => t.Id);
     config.Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
     config.Property(t => t.SourceName).HasMaxLength(50).IsRequired();
     config.Property(t => t.SourceBaseUrl).HasMaxLength(200);
 }
コード例 #9
0
        public void Configure_should_set_configuration()
        {
            var entityType = new EdmEntityType { Name = "E" };
            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object));

            entityTypeConfiguration.Configure(entityType, new EdmModel());

            Assert.Same(entityTypeConfiguration, entityType.GetConfiguration());
        }
コード例 #10
0
        public void Configure_should_throw_when_property_not_found()
        {
            var entityType = new EdmEntityType { Name = "E" };
            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object));
            var mockPropertyConfiguration = new Mock<PrimitivePropertyConfiguration>();
            entityTypeConfiguration.Property(new PropertyPath(new MockPropertyInfo()), () => mockPropertyConfiguration.Object);

            Assert.Equal(Strings.PropertyNotFound(("P"), "E"), Assert.Throws<InvalidOperationException>(() => entityTypeConfiguration.Configure(entityType, new EdmModel())).Message);
        }
コード例 #11
0
        public void GetTableName_returns_current_TableName()
        {
            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object));

            Assert.Equal(null, entityTypeConfiguration.GetTableName());

            entityTypeConfiguration.ToTable("Foo");
            Assert.Equal("Foo", entityTypeConfiguration.GetTableName().Name);
        }
コード例 #12
0
        public void Add_entity_configuration_should_add_to_model_configuration()
        {
            var modelConfiguration = new ModelConfiguration();
            var entityConfiguration = new EntityTypeConfiguration<object>();

            new ConfigurationRegistrar(modelConfiguration).Add(entityConfiguration);

            Assert.Same(entityConfiguration.Configuration, modelConfiguration.Entity(typeof(object)));
        }
コード例 #13
0
        internal static void Define(EntityTypeConfiguration<Domain.ItemInstance> config)
        {
            config.HasRequired(r => r.Item)
                .WithMany(r => r.OwnedBy)
                .HasForeignKey(fk => fk.ItemId)
                .WillCascadeOnDelete(false);

            config.HasRequired(r => r.Owner)
                .WithMany(r => r.Items)
                .HasForeignKey(fk => fk.OwnerId)
                .WillCascadeOnDelete(false);
        }
コード例 #14
0
        internal static void Define(EntityTypeConfiguration<Domain.Transaction> config)
        {
            config.HasOptional(p => p.CreditedUser)
                .WithMany(r => r.Credits)
                .HasForeignKey(fk => fk.CreditedUserId);

            config.HasOptional(p => p.DebitedUser)
                .WithMany(r => r.Debits)
                .HasForeignKey(fk => fk.DebitedUserId);

            config.Property(p => p.Amount).HasPrecision(19, 4);
        }
コード例 #15
0
 /// <summary>Defines the mapping information for the entity 'MovieNotFound'</summary>
 /// <param name="config">The configuration to modify.</param>
 protected virtual void MapMovieNotFound(EntityTypeConfiguration<MovieNotFound> config)
 {
     config.ToTable("MovieNotFound");
     config.HasKey(t => new { t.ItemId, t.ItemSource });
     config.Property(t => t.ItemId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
     config.Property(t => t.ItemSource).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
     config.Property(t => t.RowId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired();
     config.Property(t => t.ItemSearchTitle).HasMaxLength(100);
     config.Property(t => t.ItemSearchYear);
     config.Property(t => t.AddedOn);
     config.Property(t => t.ChangedOn);
 }
コード例 #16
0
        public void Configure_should_configure_entity_set_name()
        {
            var model = new EdmModel().Initialize();
            var entityType = new EdmEntityType { Name = "E" };
            var entitySet = model.AddEntitySet("ESet", entityType);

            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object)) { EntitySetName = "MySet" };

            entityTypeConfiguration.Configure(entityType, model);

            Assert.Equal("MySet", entitySet.Name);
            Assert.Same(entityTypeConfiguration, entitySet.GetConfiguration());
        }
 private static IEnumerable<IMethodTranslator> GetTranslators(EntityTypeConfiguration configuration)
 {
     return new List<IMethodTranslator>
         {
             new WhereTranslator(configuration),
             new FirstTranslator(configuration),
             new FirstOrDefaultTranslator(configuration),
             new SingleTranslator(configuration),
             new SingleOrDefaultTranslator(configuration),
             new SelectTranslator(configuration.KeyMappings),
             new TakeTranslator()
         };
 }
コード例 #18
0
        private static PropertyConfiguration GetKeyProperty(EntityTypeConfiguration 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;
        }
コード例 #19
0
ファイル: ThinkNetDbContext.cs プロジェクト: y2ket/thinknet
        private EntityTypeConfiguration<HandlerRecord> HandlerInfoConfiguration()
        {
            var config = new EntityTypeConfiguration<HandlerRecord>();

            config.HasKey(handler => new { handler.MessageId, handler.MessageTypeCode, handler.HandlerTypeCode });
            config.Property(handler => handler.MessageId).IsRequired().HasColumnType("char").HasMaxLength(36);
            config.Property(handler => handler.MessageTypeCode).IsRequired().HasColumnType("int");
            config.Property(handler => handler.HandlerTypeCode).HasColumnType("int");
            config.Property(handler => handler.Timestamp).HasColumnName("OnCreated").HasColumnType("datetime");

            config.ToTable("thinknet_handlers");

            return config;
        }
コード例 #20
0
        /// <summary>
        /// Configure LongShortUrlUser entityTypeConfiguration
        /// </summary>
        /// <param name="modelBuilder"></param>
        private static void configureEntity(EntityTypeConfiguration<LongShortUrlUser> entityTypeConfiguration)
        {
            entityTypeConfiguration.HasKey(e => e.Id);

            entityTypeConfiguration.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            entityTypeConfiguration.Property(e => e.LongShortUrlId).IsRequired();

            entityTypeConfiguration.Property(e => e.IpAddress).IsRequired().HasMaxLength(45);

            entityTypeConfiguration.Property(e => e.UserAgent).IsRequired();

            entityTypeConfiguration.Property(e => e.CreatedDate).IsRequired();

        }
コード例 #21
0
ファイル: ThinkNetDbContext.cs プロジェクト: y2ket/thinknet
        private EntityTypeConfiguration<Snapshot> SnapshotConfiguration()
        {
            var config = new EntityTypeConfiguration<Snapshot>();

            config.HasKey(snapshot => new { snapshot.AggregateRootId, snapshot.AggregateRootTypeCode });
            config.Property(snapshot => snapshot.AggregateRootId).IsRequired().HasColumnType("char").HasMaxLength(36);
            config.Property(snapshot => snapshot.AggregateRootTypeCode).IsRequired().HasColumnType("int");
            config.Property(snapshot => snapshot.Version).HasColumnType("int");
            config.Property(snapshot => snapshot.Data).HasColumnType("varchar");
            config.Property(snapshot => snapshot.Timestamp).HasColumnName("OnCreated").HasColumnType("datetime");

            config.ToTable("thinknet_snapshots");

            return config;
        }
コード例 #22
0
        public void Configure_should_configure_properties()
        {
            var entityType = new EdmEntityType { Name = "E" };
            var property = entityType.AddPrimitiveProperty("P");
            property.PropertyType.EdmType = EdmPrimitiveType.Int32;
            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object));
            var mockPropertyConfiguration = new Mock<PrimitivePropertyConfiguration>();
            var mockPropertyInfo = new MockPropertyInfo();
            property.SetClrPropertyInfo(mockPropertyInfo);
            entityTypeConfiguration.Property(new PropertyPath(mockPropertyInfo), () => mockPropertyConfiguration.Object);

            entityTypeConfiguration.Configure(entityType, new EdmModel());

            mockPropertyConfiguration.Verify(p => p.Configure(property));
        }
        public void TimestampConvention_AppliesWhenTheAttributeIsAppliedToASingleProperty()
        {
            // Arrange
            PropertyInfo property = CreateMockPropertyInfo("TestProperty");
            EntityTypeConfiguration entityType = new EntityTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);
            entityType.ExplicitProperties.Add(property, primitiveProperty);
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType);

            // Assert
            Assert.True(primitiveProperty.ConcurrencyToken);
        }
コード例 #24
0
ファイル: ThinkNetDbContext.cs プロジェクト: y2ket/thinknet
        private EntityTypeConfiguration<Event> EventDataConfiguration()
        {
            var config = new EntityTypeConfiguration<Event>();

            config.HasKey(@event => new { @event.AggregateRootId, @event.AggregateRootTypeCode, @event.Version });
            config.Property(@event => @event.AggregateRootId).IsRequired().HasColumnType("char").HasMaxLength(36);
            config.Property(@event => @event.AggregateRootTypeCode).IsRequired().HasColumnType("int");
            config.Property(@event => @event.Version).HasColumnType("int");
            config.Property(@event => @event.CorrelationId).HasColumnType("char").HasMaxLength(36);
            config.Property(@event => @event.Payload).HasColumnType("varchar");
            config.Property(@event => @event.Timestamp).HasColumnName("OnCreated").HasColumnType("datetime");

            config.ToTable("thinknet_events");

            return config;
        }
        public void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedToMultipleProperties()
        {
            // Arrange
            PropertyInfo property = CreateMockPropertyInfo("TestProperty");
            PropertyInfo otherProperty = CreateMockPropertyInfo("OtherTestProperty");
            EntityTypeConfiguration entityType = new EntityTypeConfiguration();
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);
            entityType.ExplicitProperties.Add(property, primitiveProperty);
            entityType.ExplicitProperties.Add(otherProperty, new PrimitivePropertyConfiguration(otherProperty, entityType));
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType);

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
コード例 #26
0
ファイル: SqlDbContext.cs プロジェクト: ziahamza/Wirecraft
        protected void buildCustomers(EntityTypeConfiguration<Customer> customerEntity)
        {
            customerEntity
                .HasKey(x => x.customerID)
                .Property(x => x.name).IsRequired()
                .HasMaxLength(50);

            customerEntity
                .HasMany(x => x.orders)
                .WithRequired(x => x.customer)
                .HasForeignKey(x => x.customerID)
                .WillCascadeOnDelete();

            customerEntity
                .Property(x => x.timeStamp)
                .IsRequired();
        }
コード例 #27
0
        /// <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(EntityTypeConfiguration 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 void TimestampConvention_DoesntApplyWhenTheAttributeIsAppliedToMultipleProperties_InATypeHierarchy()
        {
            // Arrange
            PropertyInfo property = CreateMockPropertyInfo("TestProperty");
            PropertyInfo otherProperty = CreateMockPropertyInfo("OtherTestProperty");
            EntityTypeConfiguration baseEntityType = new EntityTypeConfiguration();
            EntityTypeConfiguration entityType = new Mock<EntityTypeConfiguration>().SetupAllProperties().Object;
            entityType.BaseType = baseEntityType;
            PrimitivePropertyConfiguration primitiveProperty = new PrimitivePropertyConfiguration(property, entityType);
            entityType.ExplicitProperties.Add(property, primitiveProperty);
            baseEntityType.ExplicitProperties.Add(otherProperty, new PrimitivePropertyConfiguration(otherProperty, baseEntityType));
            TimestampAttributeEdmPropertyConvention convention = new TimestampAttributeEdmPropertyConvention();

            // Act
            convention.Apply(primitiveProperty, entityType, new ODataConventionModelBuilder());

            // Assert
            Assert.False(primitiveProperty.ConcurrencyToken);
        }
コード例 #29
0
        /// <summary>
        /// Configure LongShortUrl entityTypeConfiguration
        /// </summary>
        /// <param name="modelBuilder"></param>
        private static void configureEntity(EntityTypeConfiguration<LongShortUrl> entityTypeConfiguration)
        {
            entityTypeConfiguration.HasKey(e => e.Id);

            entityTypeConfiguration.Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            entityTypeConfiguration.Property(e => e.ShortUrlId).IsRequired().HasMaxLength(10);

            entityTypeConfiguration.Property(e => e.LongUrl).IsRequired().HasMaxLength(2000);

            entityTypeConfiguration.Property(e => e.CreatedDate).IsRequired();

            entityTypeConfiguration
                .HasMany(e => e.LongShortUrlUsers)
                .WithOptional()
                .HasForeignKey(e => e.LongShortUrlId)
                .WillCascadeOnDelete();

        }
コード例 #30
0
 /// <summary>Defines the mapping information for the entity 'MovieCreditResult'</summary>
 /// <param name="config">The configuration to modify.</param>
 protected virtual void MapMovieCreditResult(EntityTypeConfiguration<MovieCreditResult> config)
 {
     config.ToTable("MovieCreditResult");
     config.HasKey(t => new { t.ItemId, t.RowId });
     config.Property(t => t.ItemId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
     config.Property(t => t.RowId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
     config.Property(t => t.ItemSearchTitle).HasMaxLength(100);
     config.Property(t => t.ApiUrl).HasMaxLength(200);
     config.Property(t => t.ResultNum);
     config.Property(t => t.Name).HasMaxLength(100);
     config.Property(t => t.Order);
     config.Property(t => t.CastId).HasColumnName("Cast_Id");
     config.Property(t => t.Character).HasMaxLength(100);
     config.Property(t => t.CreditId).HasColumnName("Credit_Id").HasMaxLength(50);
     config.Property(t => t.TmdId);
     config.Property(t => t.ProfilePath).HasColumnName("Profile_Path").HasMaxLength(200);
     config.Property(t => t.AddedOn);
     config.Property(t => t.ChangedOn);
 }
コード例 #31
0
        public static IEdmModel GetEdmModel(WebRouteConfiguration configuration)
        {
            ODataConventionModelBuilder        builder = configuration.CreateConventionModelBuilder();
            EntitySetConfiguration <Employee>  entitySetConfiguration            = builder.EntitySet <Employee>("Employees");
            EntityTypeConfiguration <Manager>  entityTypeConfigurationOfManager  = builder.EntityType <Manager>();
            EntityTypeConfiguration <Employee> entityTypeConfigurationOfEmployee = builder.EntityType <Employee>();

            #region functions

            // Function bound to a collection of base EntityType.
            entityTypeConfigurationOfEmployee.Collection.Function("GetCount")
            .Returns <int>();

            // Overload
            entityTypeConfigurationOfEmployee.Collection.Function("GetCount")
            .Returns <int>()
            .Parameter <string>("Name");

            // Overload with one optional parameter
            var salaryRangeCount = entityTypeConfigurationOfEmployee.Collection.Function("GetWholeSalary")
                                   .Returns <int>();
            salaryRangeCount.Parameter <double>("minSalary");
            salaryRangeCount.Parameter <double>("maxSalary").Optional();
            salaryRangeCount.Parameter <double>("aveSalary").HasDefaultValue("8.9");

            // Function bound to a collection of derived EntityType.
            entityTypeConfigurationOfManager.Collection.Function("GetCount")
            .Returns <int>();

            // Function bound to an base EntityType
            entityTypeConfigurationOfEmployee.Function("GetEmailsCount")
            .Returns <int>();

            entityTypeConfigurationOfEmployee.Function("GetOptionalAddresses")
            .ReturnsCollection <Address>()
            .IsComposable = true;

            entityTypeConfigurationOfEmployee.Function("GetEmails")
            .ReturnsCollection <string>()
            .IsComposable = false;

            // Function bound to a derived EntityType
            entityTypeConfigurationOfManager.Function("GetEmailsCount")
            .Returns <int>();

            // Function with primitive and collection of primitive parameters
            var function = entityTypeConfigurationOfEmployee.Collection.Function("PrimitiveFunction").Returns <string>();
            function.Parameter <int>("param");
            function.Parameter <double?>("price");          // nullable
            function.Parameter <string>("name");            // nullable
            function.CollectionParameter <string>("names"); // collection with nullable element

            // Function with Enum and collection of Enum parameters
            function = entityTypeConfigurationOfEmployee.Collection.Function("EnumFunction").Returns <string>();
            function.Parameter <Color>("bkColor");
            function.Parameter <Color?>("frColor");         // nullable
            function.CollectionParameter <Color>("colors"); // collection with non-nullable element

            // Function with complex and collection of complex parameters
            function = entityTypeConfigurationOfEmployee.Collection.Function("ComplexFunction").ReturnsCollection <Address>();
            function.Parameter <Address>("address").Nullable = false;
            function.Parameter <Address>("location");            // nullable
            function.CollectionParameter <Address>("addresses"); // collection with nullable element

            // Function with entity and collection of entity parameters
            function = entityTypeConfigurationOfEmployee.Collection.Function("EntityFunction").Returns <string>();
            function.EntityParameter <Employee>("person").Nullable = false;
            function.EntityParameter <Employee>("guard");           // nullable
            function.CollectionEntityParameter <Employee>("staff"); // collection with nullable element

            #endregion

            #region actions

            // Action bound to a collection of base EntityType
            entityTypeConfigurationOfEmployee.Collection.Action("IncreaseSalary")
            .ReturnsCollectionFromEntitySet(entitySetConfiguration)
            .Parameter <string>("Name");

            // Action bound to a collection of derived EntityType
            entityTypeConfigurationOfManager.Collection.Action("IncreaseSalary")
            .ReturnsCollectionFromEntitySet(entitySetConfiguration)
            .Parameter <string>("Name");

            // Action bound to a base EntityType
            entityTypeConfigurationOfEmployee.Action("IncreaseSalary")
            .Returns <int>();

            // Action bound to a derived EntityType
            entityTypeConfigurationOfManager.Action("IncreaseSalary")
            .Returns <int>();

            // Action with optional parameters
            var action = entityTypeConfigurationOfManager.Action("IncreaseWholeSalary")
                         .Returns <int>();
            action.Parameter <double>("minSalary");
            action.Parameter <double>("maxSalary").Optional();
            action.Parameter <double>("aveSalary").HasDefaultValue("8.9");

            // Action with primitive and collection of primitive parameters
            action = entityTypeConfigurationOfEmployee.Collection.Action("PrimitiveAction");
            action.Parameter <int>("param");
            action.Parameter <double?>("price");          // nullable
            action.Parameter <string>("name");            // nullable
            action.CollectionParameter <string>("names"); // collection with nullable element

            // Action with Enum and collection of Enum parameters
            action = entityTypeConfigurationOfEmployee.Collection.Action("EnumAction");
            action.Parameter <Color>("bkColor");
            action.Parameter <Color?>("frColor");         // nullable
            action.CollectionParameter <Color>("colors"); // collection with non-nullable element

            // Action with complex and collection of complex parameters
            action = entityTypeConfigurationOfEmployee.Collection.Action("ComplexAction");
            action.Parameter <Address>("address").Nullable = false;
            action.Parameter <Address>("location");            // nullable
            action.CollectionParameter <Address>("addresses"); // collection with nullable element

            // Action with entity and collection of entity parameters
            action = entityTypeConfigurationOfEmployee.Collection.Action("EntityAction");
            action.EntityParameter <Employee>("person").Nullable = false;
            action.EntityParameter <Employee>("guard");           // nullable
            action.CollectionEntityParameter <Employee>("staff"); // collection with nullable element
            #endregion

            builder.Action("ResetDataSource");

            builder.EnumType <Color>().Namespace         = "NS";
            builder.ComplexType <Address>().Namespace    = "NS";
            builder.ComplexType <SubAddress>().Namespace = "NS";
            builder.EntityType <Employee>().Namespace    = "NS";
            builder.EntityType <Manager>().Namespace     = "NS";

            return(builder.GetEdmModel());
        }
コード例 #32
0
        internal override void Configure(
            AssociationType associationType,
            AssociationEndMember dependentEnd,
            EntityTypeConfiguration entityTypeConfiguration)
        {
            DebugCheck.NotNull(associationType);
            DebugCheck.NotNull(dependentEnd);
            DebugCheck.NotNull(entityTypeConfiguration);

            if (!_dependentProperties.Any())
            {
                return;
            }

            var dependentPropertInfos = _dependentProperties.AsEnumerable();

            if (!IsFullySpecified)
            {
                var foreignKeys
                    = from p in _dependentProperties
                      select new
                    {
                    PropertyInfo = p,
                    entityTypeConfiguration.Property(new PropertyPath(p)).ColumnOrder
                    };

                if ((_dependentProperties.Count > 1) &&
                    foreignKeys.Any(p => !p.ColumnOrder.HasValue))
                {
                    var dependentKeys = dependentEnd.GetEntityType().KeyProperties;

                    if ((dependentKeys.Count == _dependentProperties.Count) &&
                        foreignKeys.All(fk => dependentKeys.Any(p => p.GetClrPropertyInfo().IsSameAs(fk.PropertyInfo))))
                    {
                        // The FK and PK sets are equal, we know the order
                        dependentPropertInfos = dependentKeys.Select(p => p.GetClrPropertyInfo());
                    }
                    else
                    {
                        throw Error.ForeignKeyAttributeConvention_OrderRequired(entityTypeConfiguration.ClrType);
                    }
                }
                else
                {
                    dependentPropertInfos = foreignKeys.OrderBy(p => p.ColumnOrder).Select(p => p.PropertyInfo);
                }
            }

            var dependentProperties = new List <EdmProperty>();

            foreach (var dependentProperty in dependentPropertInfos)
            {
                var property
                    = dependentEnd.GetEntityType()
                      .GetDeclaredPrimitiveProperty(dependentProperty);

                if (property == null)
                {
                    throw Error.ForeignKeyPropertyNotFound(
                              dependentProperty.Name, dependentEnd.GetEntityType().Name);
                }

                dependentProperties.Add(property);
            }

            var principalEnd = associationType.GetOtherEnd(dependentEnd);

            var associationConstraint
                = new ReferentialConstraint(
                      principalEnd,
                      dependentEnd,
                      principalEnd.GetEntityType().KeyProperties,
                      dependentProperties);

            if (principalEnd.IsRequired())
            {
                associationConstraint.ToProperties.Each(p => p.Nullable = false);
            }

            associationType.Constraint = associationConstraint;
        }
コード例 #33
0
        /// <summary>
        /// Extension method for map private navigation property
        /// <example>
        ///  modelBuilder.Entity<Customer>()
        ///              .HasMany<Customer, Order>("Orders");
        /// </example>
        /// </summary>
        /// <typeparam name="TEntityType">The type of principal entity</typeparam>
        /// <typeparam name="TTargetEntityType">The type of target entity (without ICollection{})</typeparam>
        /// <param name="entityConfiguration">Associated EntityTypeConfiguration</param>
        /// <param name="navigationPropertyName">The navigation property name</param>
        /// <returns>The ManyNavigationPropertyConfiguration for this map</returns>
        public static ManyNavigationPropertyConfiguration <TEntityType, TTargetEntityType> HasMany <TEntityType, TTargetEntityType>(this EntityTypeConfiguration <TEntityType> entityConfiguration, string navigationPropertyName)
            where TEntityType : class
            where TTargetEntityType : class
        {
            var propertyInfo = typeof(TEntityType).GetProperty(navigationPropertyName,
                                                               BindingFlags.NonPublic |
                                                               BindingFlags.Instance |
                                                               BindingFlags.Public);

            if (propertyInfo != null) // if private property exists
            {
                ParameterExpression arg = Expression.Parameter(typeof(TEntityType), "parameterName");
                MemberExpression    memberExpression = Expression.Property((Expression)arg, propertyInfo);

                //Create the expression to map
                Expression <Func <TEntityType, ICollection <TTargetEntityType> > > expression = (Expression <Func <TEntityType, ICollection <TTargetEntityType> > >)Expression.Lambda(memberExpression, arg);


                return(entityConfiguration.HasMany <TTargetEntityType>(expression));
            }
            else
            {
                throw new InvalidOperationException("The property not exist");
            }
        }
コード例 #34
0
 public TreeTypeBuilder(EntityTypeConfiguration <TreeType> entity)
 {
     entity.Property(p => p.Name).IsRequired().HasMaxLength(200);
     entity.Property(p => p.Photo).IsRequired().HasMaxLength(200);
     entity.HasMany(t => t.Regions).WithMany(r => r.TreeTypes);
 }
コード例 #35
0
        private static IEdmModel GetModel()
        {
            var config = RoutingConfigurationFactory.CreateWithTypes(typeof(Customer));
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(config);

            builder.ContainerName = "C";
            builder.Namespace     = "A.B";
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;

            // bound actions
            ActionConfiguration primitive = customer.Action("Primitive");

            primitive.Parameter <int>("Quantity");
            primitive.Parameter <string>("ProductCode");
            primitive.Parameter <Date>("Birthday");
            primitive.Parameter <AColor>("BkgColor");
            primitive.Parameter <AColor?>("InnerColor");

            ActionConfiguration complex = customer.Action("Complex");

            complex.Parameter <int>("Quantity");
            complex.Parameter <MyAddress>("Address");

            ActionConfiguration enumType = customer.Action("Enum");

            enumType.Parameter <AColor>("Color");

            ActionConfiguration primitiveCollection = customer.Action("PrimitiveCollection");

            primitiveCollection.Parameter <string>("Name");
            primitiveCollection.CollectionParameter <int>("Ratings");
            primitiveCollection.CollectionParameter <TimeOfDay>("Time");
            primitiveCollection.CollectionParameter <AColor?>("Colors");

            ActionConfiguration complexCollection = customer.Action("ComplexCollection");

            complexCollection.Parameter <string>("Name");
            complexCollection.CollectionParameter <MyAddress>("Addresses");

            ActionConfiguration enumCollection = customer.Action("EnumCollection");

            enumCollection.CollectionParameter <AColor>("Colors");

            ActionConfiguration entity = customer.Action("Entity");

            entity.Parameter <int>("Id");
            entity.EntityParameter <Customer>("Customer");
            entity.EntityParameter <Customer>("NullableCustomer");

            ActionConfiguration entityCollection = customer.Action("EntityCollection");

            entityCollection.Parameter <int>("Id");
            entityCollection.CollectionEntityParameter <Customer>("Customers");

            // unbound actions
            ActionConfiguration unboundPrimitive = builder.Action("UnboundPrimitive");

            unboundPrimitive.Parameter <int>("Quantity");
            unboundPrimitive.Parameter <string>("ProductCode");
            unboundPrimitive.Parameter <Date>("Birthday");
            unboundPrimitive.Parameter <AColor>("BkgColor");
            unboundPrimitive.Parameter <AColor?>("InnerColor");

            ActionConfiguration unboundComplex = builder.Action("UnboundComplex");

            unboundComplex.Parameter <int>("Quantity");
            unboundComplex.Parameter <MyAddress>("Address");

            ActionConfiguration unboundEnum = builder.Action("UnboundEnum");

            unboundEnum.Parameter <AColor>("Color");

            ActionConfiguration unboundPrimitiveCollection = builder.Action("UnboundPrimitiveCollection");

            unboundPrimitiveCollection.Parameter <string>("Name");
            unboundPrimitiveCollection.CollectionParameter <int>("Ratings");
            unboundPrimitiveCollection.CollectionParameter <TimeOfDay>("Time");
            unboundPrimitiveCollection.CollectionParameter <AColor?>("Colors");

            ActionConfiguration unboundComplexCollection = builder.Action("UnboundComplexCollection");

            unboundComplexCollection.Parameter <string>("Name");
            unboundComplexCollection.CollectionParameter <MyAddress>("Addresses");

            ActionConfiguration unboundEnumCollection = builder.Action("UnboundEnumCollection");

            unboundEnumCollection.CollectionParameter <AColor>("Colors");

            ActionConfiguration unboundEntity = builder.Action("UnboundEntity");

            unboundEntity.Parameter <int>("Id");
            unboundEntity.EntityParameter <Customer>("Customer").Nullable = false;
            unboundEntity.EntityParameter <Customer>("NullableCustomer");

            ActionConfiguration unboundEntityCollection = builder.Action("UnboundEntityCollection");

            unboundEntityCollection.Parameter <int>("Id");
            unboundEntityCollection.CollectionEntityParameter <Customer>("Customers");

            return(builder.GetEdmModel());
        }
コード例 #36
0
 public static void AddConfiguration <TEntity>(
     this ModelBuilder modelBuilder,
     EntityTypeConfiguration <TEntity> entityConfiguration) where TEntity : class
 {
     modelBuilder.Entity <TEntity>(entityConfiguration.Configure);
 }
コード例 #37
0
        public void CanBuildBoundOperationCacheForIEdmModel()
        {
            // 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.EntityType <Blockbuster>().DerivesFrom <Movie>();
            EntityTypeConfiguration movieConfiguration        = builder.StructuralTypes.OfType <EntityTypeConfiguration>().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 = builder.Action("InCache4_MovieAction");

            incache4_MovieAction.SetBindingParameter("bindingParameter", movieConfiguration);
            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     = builder.Action("NotInCache3_NoParameters");
            ActionConfiguration notInCache4_AddressParameter = builder.Action("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
            BindableOperationFinder annotation = new BindableOperationFinder(model);

            IEdmAction[] movieActions = annotation.FindOperations(movieType)
                                        .OfType <IEdmAction>()
                                        .ToArray();
            IEdmAction[] customerActions = annotation.FindOperations(customerType)
                                           .OfType <IEdmAction>()
                                           .ToArray();
            IEdmAction[] blockBusterActions = annotation.FindOperations(blockBusterType)
                                              .OfType <IEdmAction>()
                                              .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"));
        }
コード例 #38
0
 public SectorBuilder(EntityTypeConfiguration <Sector> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(50).IsRequired();
 }
コード例 #39
0
 public EntityTypeConfigurationWrapper(EntityTypeConfiguration <TEntity> entityTypeConfiguration)
 {
     this.entityTypeConfiguration = entityTypeConfiguration;
 }
コード例 #40
0
 protected virtual void ExtendKeyIDWithOtherConfigurations(EntityTypeConfiguration <TEntity> entityConfig)
 {
 }
コード例 #41
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            if (modelBuilder == null)
            {
                throw new ArgumentNullException("modelBuilder");
            }

            // Keep this:
            modelBuilder.Entity <IdentityUser>().ToTable("AspNetUsers");

            // Change TUser to ApplicationUser everywhere else - IdentityUser
            // and ApplicationUser essentially 'share' the AspNetUsers Table in the database:
            EntityTypeConfiguration <ApplicationUser> table =
                modelBuilder.Entity <ApplicationUser>().ToTable("AspNetUsers");

            table.Property((ApplicationUser u) => u.UserName).IsRequired();

            // EF won't let us swap out IdentityUserRole for ApplicationUserRole here:
            modelBuilder.Entity <ApplicationUser>()
            .HasMany <IdentityUserRole>((ApplicationUser u) => u.Roles);
            modelBuilder.Entity <IdentityUserRole>()
            .HasKey((IdentityUserRole r) =>
                    new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");

            // Add the group stuff here:
            modelBuilder.Entity <ApplicationUser>()
            .HasMany <ApplicationUserGroup>((ApplicationUser u) => u.Groups);
            modelBuilder.Entity <ApplicationUserGroup>()
            .HasKey((ApplicationUserGroup r) =>
                    new { UserId = r.UserId, GroupId = r.GroupId }).ToTable("ApplicationUserGroups");

            // And here:
            modelBuilder.Entity <Group>()
            .HasMany <ApplicationRoleGroup>((Group g) => g.Roles);
            modelBuilder.Entity <ApplicationRoleGroup>()
            .HasKey((ApplicationRoleGroup gr) =>
                    new { RoleId = gr.RoleId, GroupId = gr.GroupId }).ToTable("ApplicationRoleGroups");

            // And Here:
            EntityTypeConfiguration <Group> groupsConfig = modelBuilder.Entity <Group>().ToTable("Groups");

            groupsConfig.Property((Group r) => r.Name).IsRequired();

            //GiangTD3:
            EntityTypeConfiguration <MenuItem> MenuItemsConfig = modelBuilder.Entity <MenuItem>().ToTable("MenuItems");
            // MenuItemsConfig.Property((MenuItem r) => r.Item_Action).IsRequired();

            EntityTypeConfiguration <MenuItemRole> MenuItemRoleConfig = modelBuilder.Entity <MenuItemRole>().ToTable("MenuItemRoles");
            //groupsConfig.Property((Group r) => r.Name).IsRequired();

            EntityTypeConfiguration <MenuItemGroup> MenuItemGroupsConfig = modelBuilder.Entity <MenuItemGroup>().ToTable("MenuItemGroups");
            // groupsConfig.Property((Group r) => r.Name).IsRequired();

            EntityTypeConfiguration <MenuItemUser> MenuItemUsersConfig = modelBuilder.Entity <MenuItemUser>().ToTable("MenuItemUsers");
            // groupsConfig.Property((Group r) => r.Name).IsRequired();

            EntityTypeConfiguration <AccountLog> AccountLogsConfig = modelBuilder.Entity <AccountLog>().ToTable("AccountLogs");

            // Leave this alone:
            EntityTypeConfiguration <IdentityUserLogin> entityTypeConfiguration =
                modelBuilder.Entity <IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
                                                                 new
            {
                UserId        = l.UserId,
                LoginProvider = l.LoginProvider,
                ProviderKey   =
                    l.ProviderKey
            }).ToTable("AspNetUserLogins");

            //entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
            EntityTypeConfiguration <IdentityUserClaim> table1 =
                modelBuilder.Entity <IdentityUserClaim>().ToTable("AspNetUserClaims");

            //table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);

            // Add this, so that IdentityRole can share a table with ApplicationRole:
            modelBuilder.Entity <IdentityRole>().ToTable("AspNetRoles");

            // Change these from IdentityRole to ApplicationRole:
            EntityTypeConfiguration <ApplicationRole> entityTypeConfiguration1 =
                modelBuilder.Entity <ApplicationRole>().ToTable("AspNetRoles");

            entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
        }
コード例 #42
0
 public ProductBuilder(EntityTypeConfiguration <Product> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(50).IsRequired();
     builder.Property(b => b.Description).HasMaxLength(4000);
 }
コード例 #43
0
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
     EntityTypeConfiguration <Category> categoryMap = modelBuilder.Entity <Category>();
     EntityTypeConfiguration <Bookmark> bookmarkMap = modelBuilder.Entity <Bookmark>();
 }
コード例 #44
0
 public PostBuilder(EntityTypeConfiguration <Post> entity) //EntityTypeConfiguration entityn fluentapi tipi
 {
     entity.Property(p => p.Photo).IsRequired().HasMaxLength(200);
     entity.Property(p => p.Description).HasMaxLength(4000);
     entity.HasRequired(p => p.Planting).WithMany(m => m.Posts).HasForeignKey(p => p.PlantingId);
 }
コード例 #45
0
        public void CanBuildOperationBoundToCollectionCacheForIEdmModel()
        {
            // 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.EntityType <Blockbuster>().DerivesFrom <Movie>();
            EntityTypeConfiguration movieConfiguration        = builder.StructuralTypes.OfType <EntityTypeConfiguration>().Single(t => t.Name == "Movie");

            // build actions that are bindable to the collection of entity
            customer.Collection.Action("CollectionCustomerActionInCache1");
            customer.Collection.Action("CollectionCustomerActionInCache2");
            movie.Collection.Action("CollectionMovieActionInCache3");

            ActionConfiguration         movieActionIncache4     = builder.Action("CollectionMovieActionInCache4");
            CollectionTypeConfiguration collectionConfiguration = new CollectionTypeConfiguration(movieConfiguration, typeof(Movie));

            movieActionIncache4.SetBindingParameter("bindingParameter", collectionConfiguration);

            blockBuster.Collection.Action("CollectionBlockbusterActionInCache5");

            // build functions that are bindable to the collection of entity
            customer.Collection.Function("CollectionCustomerFunctionInCache1").Returns <int>();
            customer.Collection.Function("CollectionCustomerFunctionInCache2").Returns <int>();
            movie.Collection.Function("CollectionMovieFunctionInCache3").Returns <int>();
            blockBuster.Collection.Function("CollectionBlockbusterFunctionInCache5").Returns <int>();

            // build actions that are either: bindable to an entity, have no parameter, have only complex parameter
            customer.Action("CustomersActionNotInCache1");
            customer.Function("CustomersFunctionNotInCache1").Returns <int>();
            movie.Action("MoviesActionNotInCache2");
            builder.Action("NoParametersNotInCache3");

            ActionConfiguration addressParameterNotInCache4 = builder.Action("AddressParameterNotInCache4");

            addressParameterNotInCache4.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
            BindableOperationFinder annotation = new BindableOperationFinder(model);
            var movieOperations       = annotation.FindOperationsBoundToCollection(movieType).ToArray();
            var customerOperations    = annotation.FindOperationsBoundToCollection(customerType).ToArray();
            var blockBusterOperations = annotation.FindOperationsBoundToCollection(blockBusterType).ToArray();

            // Assert
            Assert.Equal(3, movieOperations.Length);
            Assert.Single(movieOperations.Where(a => a.Name == "CollectionMovieActionInCache3"));
            Assert.Single(movieOperations.Where(a => a.Name == "CollectionMovieActionInCache4"));
            Assert.Single(movieOperations.Where(a => a.Name == "CollectionMovieFunctionInCache3"));

            Assert.Equal(4, customerOperations.Length);
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerActionInCache1"));
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerActionInCache2"));
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerFunctionInCache1"));
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerFunctionInCache2"));

            Assert.Equal(5, blockBusterOperations.Length);
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionBlockbusterActionInCache5"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionBlockbusterFunctionInCache5"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionMovieActionInCache3"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionMovieActionInCache4"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionMovieFunctionInCache3"));
        }
コード例 #46
0
 public override void OnModel(EntityTypeConfiguration <DelayToScheduler> entity)
 {
     entity.HasKey(r => r.Id)
     .Property(r => r.Id)
     .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
 }
        public void Can_generate_function_mappings_for_many_to_many_association_set_mapping()
        {
            var databaseMapping
                = new DbDatabaseMapping()
                  .Initialize(new EdmModel(DataSpace.CSpace), new EdmModel(DataSpace.SSpace));

            var entityType1 = databaseMapping.Model.AddEntityType("E1");

            entityType1.GetMetadataProperties().SetClrType(typeof(string));
            databaseMapping.Model.AddEntitySet("E1Set", entityType1);

            var entityType2 = databaseMapping.Model.AddEntityType("E2");

            entityType2.GetMetadataProperties().SetClrType(typeof(string));
            databaseMapping.Model.AddEntitySet("E2Set", entityType2);

            var entityTypeConfiguration = new EntityTypeConfiguration(typeof(object));

            entityTypeConfiguration.MapToStoredProcedures();
            entityType1.SetConfiguration(entityTypeConfiguration);
            entityType2.SetConfiguration(entityTypeConfiguration);

            var associationSet
                = databaseMapping.Model.AddAssociationSet(
                      "M2MSet",
                      databaseMapping.Model.AddAssociationType(
                          "M2M",
                          entityType1,
                          RelationshipMultiplicity.Many,
                          entityType2,
                          RelationshipMultiplicity.Many));

            var entitySet = new EntitySet("ES", "S", null, null, new EntityType("E", "N", 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 associationSetMapping
                = new AssociationSetMapping(
                      associationSet,
                      entitySet)
                {
                SourceEndMapping
                    = new EndPropertyMapping()
                    {
                    AssociationEnd = associationEndMember1
                    },
                TargetEndMapping
                    = new EndPropertyMapping()
                    {
                    AssociationEnd = associationEndMember2
                    }
                };

            associationSetMapping.SourceEndMapping
            .AddPropertyMapping(new ScalarPropertyMapping(new EdmProperty("PK"), new EdmProperty("FooId", TypeUsage.Create(new PrimitiveType()
            {
                DataSpace = DataSpace.SSpace
            }))));

            associationSetMapping.TargetEndMapping
            .AddPropertyMapping(new ScalarPropertyMapping(new EdmProperty("PK"), new EdmProperty("BarId", TypeUsage.Create(new PrimitiveType()
            {
                DataSpace = DataSpace.SSpace
            }))));

            var functionMappingGenerator
                = new ModificationFunctionMappingGenerator(ProviderRegistry.Sql2008_ProviderManifest);

            functionMappingGenerator.Generate(associationSetMapping, databaseMapping);

            var modificationFunctionMapping
                = associationSetMapping.ModificationFunctionMapping;

            Assert.NotNull(modificationFunctionMapping);

            var functionMapping = modificationFunctionMapping.InsertFunctionMapping;

            Assert.NotNull(functionMapping);
            Assert.Equal(2, functionMapping.ParameterBindings.Count);
            Assert.Null(functionMapping.ResultBindings);

            var function = functionMapping.Function;

            Assert.NotNull(function);
            Assert.Equal("E1E2_Insert", function.Name);
            Assert.Equal(2, function.Parameters.Count);

            functionMapping = modificationFunctionMapping.DeleteFunctionMapping;

            Assert.NotNull(functionMapping);
            Assert.Equal(2, functionMapping.ParameterBindings.Count);
            Assert.Null(functionMapping.ResultBindings);

            function = modificationFunctionMapping.DeleteFunctionMapping.Function;

            Assert.NotNull(function);
            Assert.Equal("E1E2_Delete", function.Name);
            Assert.Equal(2, function.Parameters.Count);
        }
コード例 #48
0
 public BusinessAreaBuilder(EntityTypeConfiguration <BusinessArea> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(100).IsRequired();
     builder.Property(b => b.Description).HasMaxLength(4000);
     builder.HasOptional(a => a.MainArea).WithMany(b => b.ChildAreas).HasForeignKey(a => a.MainAreaId);
 }
コード例 #49
0
ファイル: CategoryBuilder.cs プロジェクト: senasahin/Wissen
 public CategoryBuilder(EntityTypeConfiguration <Category> entity)
 {
     entity.HasKey(e => e.Id);
     entity.Property(e => e.Name).IsRequired().HasMaxLength(100);
 }
コード例 #50
0
ファイル: SagaClassMap.cs プロジェクト: tuita520/MassTransit
 protected virtual void Configure(EntityTypeConfiguration <TSaga> cfg, DbModelBuilder modelBuilder)
 {
 }
コード例 #51
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Consultation>()
            .HasMany(c => c.Symptomses).WithMany(i => i.Consultations)
            .Map(t => t.MapLeftKey("ConsultId")
                 .MapRightKey("Symptomsid")
                 .ToTable("ConsultationSymptoms"));

            modelBuilder.Entity <Consultation>()
            .HasMany(c => c.Illness).WithMany(i => i.Consultations)
            .Map(t => t.MapLeftKey("ConsultId")
                 .MapRightKey("IllnessId")
                 .ToTable("ConsultationIllness"));

            modelBuilder.Entity <Consultation>()
            .HasMany(c => c.CustLis).WithMany(i => i.consultation)
            .Map(t => t.MapLeftKey("ConsultId")
                 .MapRightKey("custId")
                 .ToTable("ConsultationMedicine"));

            modelBuilder.Entity <Consultation>()
            .HasMany(c => c.TestTypes).WithMany(i => i.Consultations)
            .Map(t => t.MapLeftKey("ConsultId")
                 .MapRightKey("TestTypeID")
                 .ToTable("ConsultTests"));

            modelBuilder.Entity <Consultation>()
            .HasMany(c => c.Drugs).WithMany(i => i.Consultations)
            .Map(t => t.MapLeftKey("ConsultId")
                 .MapRightKey("DrugId")
                 .ToTable("ConsultDrugs"));


            modelBuilder.Conventions.Remove <OneToManyCascadeDeleteConvention>();

            modelBuilder.Entity <IdentityUser>().ToTable("AspNetUsers");

            EntityTypeConfiguration <ApplicationUser> table =
                modelBuilder.Entity <ApplicationUser>().ToTable("AspNetUsers");

            table.Property((ApplicationUser u) => u.UserName).IsRequired();

            //EntityTypeConfiguration<Patient> patient_table =
            //    modelBuilder.Entity<Patient>().ToTable("AspNetUsers");

            //patient_table.Property((Patient u) => u.UserName).IsRequired();

            modelBuilder.Entity <ApplicationUser>().HasMany <IdentityUserRole>((ApplicationUser u) => u.Roles);
            //modelBuilder.Entity<Patient>().HasMany<IdentityUserRole>((Patient u) => u.Roles);

            modelBuilder.Entity <IdentityUserRole>().HasKey((IdentityUserRole r) =>
                                                            new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");

            EntityTypeConfiguration <IdentityUserLogin> entityTypeConfiguration =
                modelBuilder.Entity <IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
                                                                 new
            {
                UserId        = l.UserId,
                LoginProvider = l.LoginProvider,
                ProviderKey
                    = l.ProviderKey
            }).ToTable("AspNetUserLogins");

            modelBuilder.Entity <IdentityRole>().ToTable("AspNetRoles");

            EntityTypeConfiguration <ApplicationRole> entityTypeConfiguration1 = modelBuilder.Entity <ApplicationRole>().ToTable("AspNetRoles");

            entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
        }
コード例 #52
0
ファイル: Feedback.cs プロジェクト: walidsultan/MineRageApi
        public static void SetEntityConfiguration(DbModelBuilder modelBuilder)
        {
            EntityTypeConfiguration <TemplateDto> profileConfig = modelBuilder.Entity <TemplateDto>();

            // Entity to Table mapping
            profileConfig.ToTable("COMP_PROFILE_TEMPLATE");

            // Entity property to column name mapping
            #region - Column Mappings -
            profileConfig
            .Property(t => t.TemplateId)
            .HasColumnName("TEMPLATE_ID")
            .HasColumnOrder(1)
            .HasColumnType("NUMBER");

            profileConfig
            .Property(t => t.TemplateName)
            .HasColumnName("TEMPLATE_NAME")
            .IsRequired()
            .HasColumnOrder(2)
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.TemplateDesc)
            .HasColumnName("TEMPLATE_DESC")
            .HasMaxLength(10)
            .IsRequired()
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.CompanyCode)
            .HasColumnName("CO_CD")
            .IsRequired()
            .HasMaxLength(50)
            .IsRequired()
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.RuleSetVersion)
            .HasColumnName("TEMPLATE_FILE_NAME")
            .HasMaxLength(250)
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.CreatedBy)
            .HasColumnName("CREATED_BY")
            .IsRequired()
            .HasMaxLength(30)
            .IsRequired()
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.CreatedDt)
            .HasColumnName("CREATED_DT")
            .HasColumnType("DATE");

            profileConfig
            .Property(t => t.UpdatedBy)
            .HasColumnName("UPDATED_BY")
            .IsRequired()
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.UpdatedDt)
            .HasColumnName("UPDATED_DT")
            .IsRequired()
            .HasColumnType("DATE");

            profileConfig
            .Property(t => t.ProfileTemplate)
            .HasColumnName("PROFILE_TEMPLATE")
            .HasMaxLength(100)
            .HasColumnType("CLOB");

            profileConfig
            .Property(t => t.Status)
            .HasColumnName("STATUS")
            .HasMaxLength(15)
            .HasColumnType("VARCHAR2");

            profileConfig
            .Property(t => t.TemplateGuid)
            .HasColumnName("TEMPLATE_GUID")
            .IsRequired()
            .HasColumnType("RAW");

            profileConfig
            .Property(t => t.TemplateVersion)
            .HasColumnName("TEMPLATE_VERSION")
            .HasColumnType("NUMBER");

            #endregion

            // Set Primary key
            profileConfig.HasKey(tz => new { tz.TemplateId });
        }
コード例 #53
0
 public CompanyTypeBuilder(EntityTypeConfiguration <CompanyType> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(50).IsRequired();
 }
コード例 #54
0
 public TreeTypeBuilder(EntityTypeConfiguration <TreeType> entity)
 {
     entity.Property(p => p.Name).IsRequired().HasMaxLength(200);
     entity.Property(p => p.Photo).IsRequired().HasMaxLength(200);
     entity.HasRequired(p => p.Region).WithMany(m => m.TreeTypes).HasForeignKey(p => p.RegionId).WillCascadeOnDelete(false);
 }
コード例 #55
0
ファイル: UserGroupBuilder.cs プロジェクト: BusraOzdmr/MiniQM
 public UserGroupBuilder(EntityTypeConfiguration <UserGroup> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(100).IsRequired();
     builder.Property(b => b.Description).HasMaxLength(4000);
     builder.HasOptional(a => a.Language).WithMany(b => b.UserGroups).HasForeignKey(a => a.LanguageId);
 }
 public static void AddConfiguration <TEntity>(
     this ModelBuilder modelBuilder,
     EntityTypeConfiguration <TEntity> configuration) where TEntity : class
 {
     configuration.Map(modelBuilder.Entity <TEntity>());
 }
コード例 #57
0
 public PurchasingDepartmentBuilder(EntityTypeConfiguration <PurchasingDepartment> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(100).IsRequired();
     builder.HasRequired(a => a.Company).WithMany(b => b.PurchasingDepartments).HasForeignKey(a => a.CompanyId);
 }
コード例 #58
0
 public LicenseBuilder(EntityTypeConfiguration <LicenseEntity> modelBuilder)
 {
     modelBuilder.ToTable(TableName);
     modelBuilder.HasIndex(b => b.Id);
 }
コード例 #59
0
ファイル: CityBuilder.cs プロジェクト: koseirem1/MyErp
 public CityBuilder(EntityTypeConfiguration <City> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(50).IsRequired();
     builder.HasRequired(a => a.Country).WithMany(b => b.Cities).HasForeignKey(a => a.CountryId);
 }
コード例 #60
0
 public DocumentBuilder(EntityTypeConfiguration <Document> builder)
 {
     builder.Property(b => b.Name).HasMaxLength(100).IsRequired();
     builder.Property(b => b.File).HasMaxLength(200).IsRequired();
     builder.Property(b => b.Description).HasMaxLength(4000);
 }