public void ShouldAllowConventionsToAlterBiDirectionalTableNames()
        {
            var model = new PersistenceModel();
            var leftMap = new ClassMap<Left>();

            leftMap.Id(x => x.Id);
            leftMap.HasManyToMany(x => x.Rights);

            var rightMap = new ClassMap<Right>();

            rightMap.Id(x => x.Id);
            rightMap.HasManyToMany(x => x.Lefts);

            model.Add(leftMap);
            model.Add(rightMap);
            model.Conventions.Add<TestTableNameConvention>();

            var mappings = model.BuildMappings();

            var leftMapping = mappings.SelectMany(x => x.Classes).Where(x => x.Type == typeof(Left)).First();
            var rightMapping = mappings.SelectMany(x => x.Classes).Where(x => x.Type == typeof(Right)).First();

            leftMapping.Collections.First().TableName.ShouldEqual("Lefts_Rights");
            rightMapping.Collections.First().TableName.ShouldEqual("Lefts_Rights");
        }
        public void CanCreateClassMap()
        {
            var classMap = new ClassMap<Artist>();
            ClassMapping mapping = classMap.GetClassMapping();

            mapping.Type.ShouldEqual(typeof(Artist));
        }
 public void SetUp()
 {
     tourMap = new ClassMap<Tour>(Version.LUCENE_30);
     tourMap.Property(p => p.AccommodationAges).Stored().NotAnalyzed();
     tourMap.Property(p => p.TotalPriceMin).Stored().NotAnalyzed();
     tourMap.Property(p => p.TotalPriceMax).Stored().NotAnalyzed();
 }
        public void ShouldHaveSameTableNameForBothSidesOfMappingWhenRightSpecified()
        {
            var model = new PersistenceModel();
            var leftMap = new ClassMap<Left>();

            leftMap.Id(x => x.Id);
            leftMap.HasManyToMany(x => x.Rights);

            var rightMap = new ClassMap<Right>();

            rightMap.Id(x => x.Id);
            rightMap.HasManyToMany(x => x.Lefts)
                .Table("MyJoinTable");

            model.Add(leftMap);
            model.Add(rightMap);

            var mappings = model.BuildMappings();

            var leftMapping = mappings.SelectMany(x => x.Classes).Where(x => x.Type == typeof(Left)).First();
            var rightMapping = mappings.SelectMany(x => x.Classes).Where(x => x.Type == typeof(Right)).First();

            leftMapping.Collections.First().TableName.ShouldEqual("MyJoinTable");
            rightMapping.Collections.First().TableName.ShouldEqual("MyJoinTable");
        }
示例#5
0
        public void GenerateIdsFor(object entity, ClassMap classMap)
        {
            this.currentClassMap = classMap;
            this.currentEntity = entity;

            this.Visit(classMap);
        }
        private void Mapping(Action<KeyManyToOnePart> mappingDefinition)
        {
            var classMap = new ClassMap<ExampleClass>();
            var map = classMap.CompositeId()
                .KeyProperty(x => x.Id)
                .KeyReference(x => x.Parent, mappingDefinition);

            mapping = classMap;
        }
 public void AlwaysShouldSetDefaultLazyToTrue()
 {
     var classMap = new ClassMap<Target>();
     classMap.Id(x => x.Id);
     model.Add(classMap);
     model.Conventions.Add(DefaultLazy.Always());
     model.BuildMappings()
         .First()
         .DefaultLazy.ShouldBeTrue();
 }
        public void CanMapProperty()
        {
            var classMap = new ClassMap<Artist>();
            classMap.Map(x => x.Name);
            ClassMapping mapping = classMap.GetClassMapping();

            var property = mapping.Properties.FirstOrDefault();
            property.ShouldNotBeNull();
            property.MappedMember.ShouldEqual(ReflectionHelper.GetMember<Artist>(x => x.Name));
        }
        public void CanMapReference()
        {
            var classMap = new ClassMap<Album>();
            classMap.References(x => x.Artist);
            ClassMapping mapping = classMap.GetClassMapping();

            var reference = mapping.References.FirstOrDefault();
            reference.ShouldNotBeNull();
            reference.MappedMember.ShouldEqual(ReflectionHelper.GetMember<Album>(x => x.Artist));
        }
 public void ShouldSetDefaultAccessToValue()
 {
     var classMap = new ClassMap<Target>();
     classMap.Id(x => x.Id);
     model.Add(classMap);
     model.Conventions.Add(DefaultAccess.Field());
     model.BuildMappings()
         .First()
         .DefaultAccess.ShouldEqual("field");
 }
 public void NeverShouldSetDefaultLazyToFalse()
 {
     var classMap = new ClassMap<Target>();
     classMap.Id(x => x.Id);
     model.Add(classMap);
     model.Conventions.Add(DefaultLazy.Never());
     model.BuildMappings()
         .First()
         .DefaultLazy.ShouldBeFalse();
 }
        public void CanMapCollection()
        {
            var classMap = new ClassMap<Artist>();
            classMap.HasMany<Album>(x => x.Albums);
            ClassMapping mapping = classMap.GetClassMapping();

            var collection = mapping.Collections.FirstOrDefault() as BagMapping;
            collection.ShouldNotBeNull();
            collection.MappedMember.ShouldEqual(ReflectionHelper.GetMember<Artist>(x => x.Albums));
        }
 public void ShouldSetDefaultAccessToValue()
 {
     var classMap = new ClassMap<Target>();
     classMap.Id(x => x.Id);
     model.Add(classMap);
     model.Conventions.Add(AutoImport.Never());
     model.BuildMappings()
         .First()
         .AutoImport.ShouldEqual(false);
 }
        public Document CreateDocument(ClassMap classMap, object entity)
        {
            if (entity == null)
                throw new ArgumentNullException("entity");
            this.entity = entity;

            this.document = new Document();
            classMap.Accept(this);

            return this.document;
        }
        private void Mapping(Action<ComponentPart<ComponentTarget>> mappingDefinition)
        {
            var classMap = new ClassMap<PropertyTarget>();
            classMap.Id(x => x.Id);
            var map = classMap.Component(x => x.Component, mappingDefinition);

            mappingDefinition(map);

            mapping = classMap;
            mappingType = typeof(PropertyTarget);
        }
        public override void establish_context()
        {
            inline_component = new ClassMap<Target>();
            inline_component.Component(x => x.ComponentProperty, c => c.Map(x => x.Property));

            external_component = new ComponentMap<Component>();
            external_component.Map(x => x.Property);

            reference_component = new ClassMap<Target>();
            reference_component.Component(x => x.ComponentProperty);
        }
        private void VerifyModel(Action<HibernateMapping> modelVerification)
        {
            var classMap = new ClassMap<ExampleClass>();

            model.Add(classMap);

            var generatedModels = model.BuildMappings();
            var modelInstance = generatedModels
                .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ExampleClass)) != null);

            modelVerification(modelInstance);
        }
        public void CanMapTablePerClass()
        {
            var classMap = new ClassMap<Employee>();
            classMap.JoinedSubClass<SalaryEmployee>("SalaryEmployeeID", salaryMap => salaryMap.Map(x => x.Salary));

            var classmapping = classMap.GetClassMapping();
            var salaryMapping = classmapping.Subclasses.FirstOrDefault() as JoinedSubclassMapping;
            salaryMapping.ShouldNotBeNull();
            salaryMapping.Type.ShouldEqual(typeof (SalaryEmployee));
            salaryMapping.Key.Column.ShouldEqual("SalaryEmployeeID");
            salaryMapping.Properties.ShouldHaveCount(1);
        }
示例#19
0
        public MemberMap(ClassMap classMap, MemberInfo memberInfo)
        {
            ClassMap = classMap;
            MemberInfo = memberInfo;

            Type = memberInfo is PropertyInfo
                    ? (memberInfo as PropertyInfo).PropertyType
                    : ((FieldInfo) memberInfo).FieldType;

            ColumnName = GetColumnName(memberInfo);
            ValueSerializer = ValueSerializerProvider.GetSerializer(Type);
        }
        public override void establish_context()
        {
            var component_map = new ComponentMap<Component>();
            component_map.Map(x => x.Property);

            var class_map = new ClassMap<Target>();
            class_map.Component(x => x.Component);

            persistence_model = new PersistenceModel();
            persistence_model.Add(class_map);
            persistence_model.Add(component_map);
        }
        public void AlwaysShouldSetDefaultLazyToTrue()
        {
            var classMap = new ClassMap<Target>();
            classMap.Id(x => x.Id);
            model.Add(classMap);
            model.Conventions.Add(DefaultLazy.Always());
            model.Conventions.Add(DefaultCascade.All());
            
            var mapping = model.BuildMappings().First();

            mapping.DefaultLazy.ShouldBeTrue();
            mapping.DefaultCascade.ShouldEqual("all");
        }
示例#22
0
        public MemberMap(ClassMap classMap, MemberInfo memberInfo)
        {
            ClassMap = classMap;
            MemberInfo = memberInfo;

            Type = memberInfo is PropertyInfo
                    ? (memberInfo as PropertyInfo).PropertyType
                    : ((FieldInfo) memberInfo).FieldType;

            ColumnName = GetColumnName(memberInfo);
            ValueSerializer = ValueSerializerProvider.GetSerializer(Type);
			DefaultValue = Type.IsValueType ? Activator.CreateInstance(Type) : null;
        }
        public void ShouldSetForeignKeyOnJoin()
        {
            var classMap = new ClassMap<ExampleInheritedClass>();

            classMap.Join("two", m => {});

            model.Add(classMap);

            model.BuildMappings()
                .First()
                .Classes.First()
                .Joins.First()
                .Key.Columns.First().Name.ShouldEqual("ExampleInheritedClass!");
        }
        public void ShouldSetForeignKeyOnManyToMany()
        {
            var classMap = new ClassMap<ExampleInheritedClass>();

            classMap.HasManyToMany(x => x.Children);

            model.Add(classMap);

            model.BuildMappings()
                .First()
                .Classes.First()
                .Collections.First()
                .Key.Columns.First().Name.ShouldEqual("ExampleInheritedClass!");
        }
        public void CanMapComponent()
        {
            var classMap = new ClassMap<SalaryEmployee>();
            classMap.Component(x => x.Salary, c =>
                {
                    c.Map(x => x.Amount);
                    c.Map(x => x.Currency);
                });

            var classmapping = classMap.GetClassMapping();
            ComponentMapping componentMapping = classmapping.Components.FirstOrDefault();
            componentMapping.ShouldNotBeNull();
            componentMapping.Properties.ShouldHaveCount(2);
        }
        public void ShouldSetForeignKeyOnManyToOne()
        {
            var classMap = new ClassMap<ExampleClass>();

            classMap.References(x => x.Parent);

            model.Add(classMap);

            model.BuildMappings()
                .First()
                .Classes.First()
                .References.First()
                .Columns.First().Name.ShouldEqual("Parent!");
        }
        public void ShouldSetForeignKeyOnJoinedSubclasses()
        {
            var classMap = new ClassMap<ExampleClass>();
            var subclassMap = new SubclassMap<ExampleInheritedClass>();

            model.Add(classMap);
            model.Add(subclassMap);

            model.BuildMappings()
                .First()
                .Classes.First()
                .Subclasses.Cast<JoinedSubclassMapping>().First()
                .Key.Columns.First().Name.ShouldEqual("ExampleClass!");
        }
        public void ShouldntDuplicateJoinMapping()
        {
            var model = new PersistenceModel();
            var classMap = new ClassMap<Target>();

            classMap.Id(x => x.Id);
            classMap.Join("other", m => m.Map(x => x.Property));

            model.Add(classMap);
            model.Configure(cfg);

            cfg.ClassMappings.First()
                .JoinClosureIterator.Count().ShouldEqual(1);
        }
        private void VerifyModel(Action<VersionMapping> modelVerification)
        {
            var classMap = new ClassMap<ValidVersionClass>();
            var map = classMap.Version(x => x.Version);

            model.Add(classMap);

            var generatedModels = model.BuildMappings();
            var modelInstance = generatedModels
                .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ValidVersionClass)) != null)
                .Classes.First()
                .Version;

            modelVerification(modelInstance);
        }
        private void VerifyModel(Action<CompositeIdMapping> modelVerification)
        {
            var classMap = new ClassMap<ExampleClass>();
            var map = classMap.CompositeId(x => x.Id);

            model.Add(classMap);

            var generatedModels = model.BuildMappings();
            var modelInstance = generatedModels
                .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ExampleClass)) != null)
                .Classes.First()
                .Id;

            modelVerification((CompositeIdMapping)modelInstance);
        }
        /// <inheritdoc />
        public Task <PagedList <T> > ReadList <T>(object whereConditions, object sortOrders, int pageSize, int pageNumber) where T : class
        {
            ClassMap classMap = ClassMapper.GetClassMap <T>();

            // get the candidate objects
            IEnumerable <T> filteredT;
            IDictionary <string, object> whereDict = classMap.CoalesceToDictionary(whereConditions);

            if (whereDict.Count == 0)
            {
                filteredT = this.ReadAll <T>().GetAwaiter().GetResult();
            }
            else
            {
                filteredT = this.ReadList <T>(whereConditions).GetAwaiter().GetResult();
            }

            return(Task.FromResult(this.GetPage <T>(filteredT, sortOrders, pageSize, pageNumber)));
        }
示例#32
0
            public void DoesNotGenerateReadonlyColumns()
            {
                Mock <IPropertyMap> property1 = new Mock <IPropertyMap>();

                property1.Setup(p => p.IsReadOnly).Returns(true).Verifiable();

                Mock <IPropertyMap> property2 = new Mock <IPropertyMap>();

                property2.Setup(p => p.KeyType).Returns(KeyType.NotAKey).Verifiable();
                property2.Setup(p => p.Name).Returns("Name").Verifiable();

                List <IPropertyMap> properties = new List <IPropertyMap>
                {
                    property1.Object,
                    property2.Object
                };

                ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable();

                Generator.Setup(g => g.GetColumnName(ClassMap.Object, property2.Object, false)).Returns("Column").Verifiable();
                Generator.Setup(g => g.GetTableName(ClassMap.Object)).Returns("TableName").Verifiable();

                Dialect.SetupGet(d => d.SupportsMultipleStatements).Returns(false).Verifiable();

                Mock <IPredicate>           predicate  = new Mock <IPredicate>();
                Dictionary <string, object> parameters = new Dictionary <string, object>();

                predicate.Setup(p => p.GetSql(Generator.Object, parameters)).Returns("Predicate").Verifiable();

                var result = Generator.Object.Update(ClassMap.Object, predicate.Object, parameters, false);

                Assert.AreEqual("UPDATE TableName SET Column = @Name WHERE Predicate", result);

                predicate.Verify();
                ClassMap.Verify();
                property1.Verify();
                property1.VerifyGet(p => p.Name, Times.Never());
                property2.Verify();

                Generator.Verify();
                Generator.Verify(g => g.GetColumnName(ClassMap.Object, property1.Object, false), Times.Never());
            }
示例#33
0
            public void DoesNotGenerateReadonlyColumns()
            {
                Mock <IMemberMap> property1 = new Mock <IMemberMap>();

                property1.Setup(p => p.IsReadOnly).Returns(true).Verifiable();

                Mock <IMemberMap> property2 = new Mock <IMemberMap>();

                property2.Setup(p => p.KeyType).Returns(KeyType.NotAKey).Verifiable();
                property2.Setup(p => p.Name).Returns("Name").Verifiable();

                List <IMemberMap> properties = new List <IMemberMap>
                {
                    property1.Object,
                    property2.Object
                };

                ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable();

                SetupGenerator();

                Dialect.SetupGet(d => d.SupportsMultipleStatements).Returns(false).Verifiable();

                var parameters = new Dictionary <string, object>();
                Mock <IPredicate> predicate = new Mock <IPredicate>();

                predicate.Setup(p => p.GetSql(It.IsAny <ISqlGenerator>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <bool>()))
                .Returns("Predicate").Verifiable();

                var result = Generator.Object.Update(ClassMap.Object, predicate.Object, parameters, false, null);

                StringAssert.AreEqualIgnoringCase("UPDATE TableName SET Column = @u_1 WHERE Predicate", result);

                predicate.Verify();
                ClassMap.Verify();
                property1.Verify();
                property1.VerifyGet(p => p.Name, Times.Once());
                property2.Verify();

                Generator.Verify();
                Generator.Verify(g => g.GetColumnName(It.IsAny <IColumn>(), It.IsAny <bool>(), It.IsAny <bool>()), Times.Once());
            }
示例#34
0
            public void WithSort_GeneratesSql()
            {
                Mock <IMemberMap> property1 = new Mock <IMemberMap>();

                property1.SetupGet(p => p.Ignored).Returns(true).Verifiable();
                property1.SetupGet(p => p.ClassMapper).Returns(ClassMap.Object).Verifiable();
                Mock <IMemberMap> property2 = new Mock <IMemberMap>();

                property2.SetupGet(p => p.ClassMapper).Returns(ClassMap.Object).Verifiable();
                var properties = new List <IMemberMap>
                {
                    property1.Object,
                    property2.Object
                };

                ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable();

                IDictionary <string, object> parameters = new Dictionary <string, object>();
                Mock <ISort> sortField = new Mock <ISort>();

                sortField.SetupGet(s => s.PropertyName).Returns("SortProperty").Verifiable();
                sortField.SetupGet(s => s.Ascending).Returns(true).Verifiable();
                List <ISort> sort = new List <ISort>
                {
                    sortField.Object
                };

                Generator.Setup(g => g.GetTables(It.IsAny <IClassMapper>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <IList <IReferenceMap> >()))
                .Returns("TableName").Verifiable();
                Generator.Setup(g => g.BuildSelectColumns(It.IsAny <IClassMapper>(), It.IsAny <IList <IProjection> >(), It.IsAny <IList <IReferenceMap> >())).Returns("Columns").Verifiable();
                Generator.Setup(g => g.GetColumnName(ClassMap.Object, "SortProperty", false, true)).Returns("SortColumn").Verifiable();

                Dialect.Setup(d => d.GetPagingSql("SELECT Columns FROM TableName ORDER BY SortColumn ASC", 2, 10, parameters, null)).Returns("PagedSQL").Verifiable();

                var result = Generator.Object.SelectPaged(ClassMap.Object, null, sort, 2, 10, parameters, null);

                StringAssert.AreEqualIgnoringCase("PagedSQL", result);
                ClassMap.Verify();
                sortField.Verify();
                Generator.Verify();
                Dialect.Verify();
            }
示例#35
0
        private static void PopulateULinqAssociation(ClassMap mapping, MemberInfo p, object a)
        {
            var thisKey      = ULinq.Instance.Association.ThisKey(a) as string;
            var otherKey     = ULinq.Instance.Association.OtherKey(a) as string;
            var isForeignKey = (bool)ULinq.Instance.Association.IsForeignKey(a);

            var associationMapper = isForeignKey
                ? new UWay.Skynet.Cloud.Data.ManyToOneAttribute() as AbstractAssociationAttribute
                : new UWay.Skynet.Cloud.Data.OneToManyAttribute();

            if (!string.IsNullOrEmpty(thisKey))
            {
                associationMapper.ThisKey = thisKey;
            }
            if (!string.IsNullOrEmpty(otherKey))
            {
                associationMapper.OtherKey = otherKey;
            }
            mapping.members.Add(p, associationMapper);
        }
        private void RegisterClassMap()
        {
            ClassMap <UnitReceiptNoteViewModel> .Register();

            ClassMap <UnitReceiptNoteItemViewModel> .Register();

            ClassMap <UnitViewModel> .Register();

            ClassMap <DivisionViewModel> .Register();

            ClassMap <CategoryViewModel> .Register();

            ClassMap <ProductViewModel> .Register();

            ClassMap <UomViewModel> .Register();

            ClassMap <PurchaseOrderViewModel> .Register();

            ClassMap <SupplierViewModel> .Register();
        }
示例#37
0
            public void GeneratesSql()
            {
                Mock <IPropertyMap> property1 = new Mock <IPropertyMap>();
                Mock <IPropertyMap> property2 = new Mock <IPropertyMap>();
                var properties = new List <IPropertyMap>
                {
                    property1.Object,
                    property2.Object
                };

                Generator.Setup(g => g.GetColumnName(ClassMap.Object, property1.Object, true)).Returns("Column1").Verifiable();
                Generator.Setup(g => g.GetColumnName(ClassMap.Object, property2.Object, true)).Returns("Column2").Verifiable();
                ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable();

                var result = Generator.Object.BuildSelectColumns(ClassMap.Object);

                Assert.AreEqual("Column1, Column2", result);
                ClassMap.Verify();
                Generator.Verify();
            }
        private void VerifyModel(Action <SubclassMapping> modelVerification)
        {
            var classMap = new ClassMap <ExampleClass>();

            classMap.Id(x => x.Id);
            classMap.DiscriminateSubClassesOnColumn("col");

            var subclassMap = new SubclassMap <ExampleInheritedClass>();

            model.Add(classMap);
            model.Add(subclassMap);

            var generatedModels = model.BuildMappings();
            var modelInstance   = generatedModels
                                  .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(ExampleClass)) != null)
                                  .Classes.First()
                                  .Subclasses.First();

            modelVerification((SubclassMapping)modelInstance);
        }
示例#39
0
        /// <summary>
        /// 注册实体到数据表的映射关系
        /// </summary>
        /// <param name="classMap"></param>
        /// <returns></returns>
        public DbConfiguration AddClass(ClassMap classMap)
        {
            Guard.NotNull(classMap, "classMap");
            var entityType   = classMap.EntityType;
            var entityTypeId = entityType.TypeHandle.Value;

            if (mappings.ContainsKey(entityTypeId))
            {
                throw new RepeatRegistrationException("Repeat register entity mapping for entity '" + entityType.FullName + "'.");
            }

            var mapping = classMap.CreateMapping();

            Guard.NotNull(mapping, "entity");

            AutoMapping(mapping.entityType, mapping);

            RegistyMapping(mapping);
            return(this);
        }
示例#40
0
        private void VerifyModel(Action <DynamicComponentMapping> modelVerification)
        {
            var classMap = new ClassMap <PropertyTarget>();
            var map      = classMap.DynamicComponent(x => x.ExtensionData, m =>
            {
                m.Map(x => (string)x["Name"]);
                m.Map(x => (int)x["Age"]);
                m.Map(x => (string)x["Profession"]);
            });

            model.Add(classMap);

            var generatedModels = model.BuildMappings();
            var modelInstance   = (DynamicComponentMapping)generatedModels
                                  .First(x => x.Classes.FirstOrDefault(c => c.Type == typeof(PropertyTarget)) != null)
                                  .Classes.First()
                                  .Components.Where(x => x is DynamicComponentMapping).First();

            modelVerification(modelInstance);
        }
        public ClassMap <TType> Load <TType>()
        {
            if (FluentDynamoDbConfiguration.ClassMapLocationAssembly == null)
            {
                throw new FluentDynamoDbMappingException(
                          string.Format(
                              "ClassMapLocationAssembly was not provided, you should run FluentDynamoDbConfiguration.Configure() to define a assembly location for mappers"));
            }

            var mappingType =
                FluentDynamoDbConfiguration.ClassMapLocationAssembly.GetTypes()
                .FirstOrDefault(t => t.IsSubclassOf(typeof(ClassMap <TType>)));

            if (mappingType == null)
            {
                throw new FluentDynamoDbMappingException(string.Format("Could not find mapping for class of type {0}",
                                                                       typeof(TType)));
            }

            ClassMap <TType> mapping = null;

            try
            {
                mapping = Activator.CreateInstance(mappingType) as ClassMap <TType>;
                if (mapping == null)
                {
                    throw new FluentDynamoDbMappingException(
                              string.Format(
                                  "Could not create a instance of type {0}, class must provide a public constructor",
                                  mappingType));
                }
            }
            catch (MissingMethodException ex)
            {
                throw new FluentDynamoDbMappingException(
                          string.Format("Could not create a instance of type {0}, class must provide a public constructor",
                                        mappingType), ex);
            }

            return(mapping);
        }
        private PagedList <T> GetPage <T>(IEnumerable <T> results, object sortOrders, int pageSize, int pageNumber) where T : class
        {
            ClassMap classMap = ClassMapper.GetClassMap <T>();

            // create the paging variables
            int firstRow = ((pageNumber - 1) * pageSize) + 1;
            int lastRow  = firstRow + (pageSize - 1);
            int total    = results.Count();

            // validate / build the ordering string
            string ordering = string.Empty;
            IDictionary <string, SortOrder> sortOrderDict = classMap.CoalesceSortOrderDictionary(sortOrders);

            for (int i = 0; i < sortOrderDict.Count; i++)
            {
                // check whether this property exists for the type
                string propertyName = sortOrderDict.Keys.ElementAt(i);
                if (!classMap.AllProperties.ContainsKey(propertyName))
                {
                    throw new ArgumentException($"Failed to find property {propertyName} on {classMap.Name}");
                }

                ordering += string.Format(
                    "{0}{1}{2}",
                    propertyName,
                    sortOrderDict[propertyName] == SortOrder.Descending ? " desc" : string.Empty,
                    i != sortOrderDict.Count - 1 ? "," : string.Empty);
            }

            // order the rows and take the results for this page
            results = results.AsQueryable <T>().OrderBy(ordering).Skip(firstRow - 1).Take(pageSize);

            return(new PagedList <T>()
            {
                Rows = results,
                HasNext = lastRow < total,
                HasPrevious = firstRow > 1,
                TotalPages = (total / pageSize) + ((total % pageSize) > 0 ? 1 : 0),
                TotalRows = total
            });
        }
示例#43
0
        /// <summary>
        /// Creates the member assignments for the given <see cref="ClassMap"/>.
        /// </summary>
        /// <param name="mapping">The mapping to create the assignments for.</param>
        /// <param name="assignments">The assignments that will be added to from the mapping.</param>
        public virtual void CreateMemberAssignmentsForMapping(ClassMap mapping, List <MemberAssignment> assignments)
        {
            foreach (var memberMap in mapping.MemberMaps)
            {
                var fieldExpression = CreateGetFieldExpression(memberMap);
                if (fieldExpression == null)
                {
                    continue;
                }

                assignments.Add(Expression.Bind(memberMap.Data.Member, fieldExpression));
            }

            foreach (var referenceMap in mapping.ReferenceMaps)
            {
                if (!reader.CanRead(referenceMap))
                {
                    continue;
                }

                Expression referenceBody;
                if (referenceMap.Data.Mapping.ParameterMaps.Count > 0)
                {
                    var arguments = new List <Expression>();
                    CreateConstructorArgumentExpressionsForMapping(referenceMap.Data.Mapping, arguments);
                    var args = new GetConstructorArgs
                    {
                        ClassType = referenceMap.Data.Mapping.ClassType,
                    };
                    referenceBody = Expression.New(reader.Configuration.GetConstructor(args), arguments);
                }
                else
                {
                    var referenceAssignments = new List <MemberAssignment>();
                    CreateMemberAssignmentsForMapping(referenceMap.Data.Mapping, referenceAssignments);
                    referenceBody = CreateInstanceAndAssignMembers(referenceMap.Data.Member.MemberType(), referenceAssignments);
                }

                assignments.Add(Expression.Bind(referenceMap.Data.Member, referenceBody));
            }
        }
示例#44
0
        // build RDF that's rooted at className with classIdentifier
        private XElement BuildRdfXml(string startClassName, string startClassIdentifier)
        {
            ClassTemplateMap classTemplateMap = _graphMap.GetClassTemplateMapByName(startClassName);

            if (classTemplateMap != null)
            {
                ClassMap           classMap     = classTemplateMap.classMap;
                List <TemplateMap> templateMaps = classTemplateMap.templateMaps;

                if (classMap != null)
                {
                    bool          hasRelatedProperty;
                    List <string> classIdentifiers = GetClassIdentifiers(classMap, 0, out hasRelatedProperty);

                    ProcessOutboundClass(0, startClassName, startClassIdentifier, true, classIdentifiers,
                                         hasRelatedProperty, classTemplateMap.classMap, classTemplateMap.templateMaps);
                }
            }

            return(_rdfXml);
        }
示例#45
0
        /// <summary>
        /// Reads records from a CSV returning a list of the object type passed. Automapping is used if a Map is configured in settings.
        /// </summary>
        /// <typeparam name="T">The record type.</typeparam>
        /// <param name="csvFile">The CSV file to read.</param>
        /// <param name="classMap">The class map to use, null if not needed.</param>
        /// <param name="settings">The settings.</param>
        /// <returns>List of defined type.</returns>
        public IEnumerable <T> ReadRecords <T>(FilePath csvFile, ClassMap classMap, CsvHelperSettings settings)
        {
            if (csvFile == null)
            {
                throw new ArgumentNullException(nameof(csvFile));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            var file = GetFile(csvFile);

            using (var textReader = new StreamReader(file.OpenRead()))
                using (var csvReader = new CsvReader(textReader)) {
                    if (classMap != null)
                    {
                        csvReader.Configuration.RegisterClassMap(classMap);
                    }
                    return(csvReader.GetRecords <T>().ToList());
                }
        }
示例#46
0
        public virtual MappingTester <T> ForMapping(ClassMap <T> classMap)
        {
            if (classMap != null)
            {
                model.Add(classMap);
            }

            var mappings     = model.BuildMappings();
            var foundMapping = mappings.FirstOrDefault(x => x.Classes.FirstOrDefault(c => c.Type == typeof(T)) != null);

            if (foundMapping == null)
            {
                throw new InvalidOperationException("Could not find mapping for class '" + typeof(T).Name + "'");
            }

            document = new MappingXmlSerializer()
                       .Serialize(foundMapping);
            currentElement = document.DocumentElement;

            return(this);
        }
        public void ComponentWithPropertiesShouldAddToModelComponentsCollection()
        {
            var classMap = new ClassMap <Parent>();

            classMap.Id(x => x.Id);

            var subclassMap = new SubclassMap <Child>();

            subclassMap.Component(x => x.Component, c => c.Map(x => x.Name));

            var model = new PersistenceModel();

            model.Add(classMap);
            model.Add(subclassMap);

            model.BuildMappings()
            .First()
            .Classes.First()
            .Subclasses.First()
            .Components.Count().ShouldEqual(1);
        }
        private int GetDecimalPoints(ClassMap mapper, ModelProperty modelProperty)
        {
            if (mapper == null || modelProperty == null)
            {
                return(2);
            }

            MemberMap memberMap = mapper.MemberMaps.SingleOrDefault(x => x.Data.Names.Names.Intersect(modelProperty.Names).Any());

            string[] format = memberMap?.Data?.TypeConverterOptions?.Formats ?? new[] { "0.00" };
            if (format.Length > 0)
            {
                string[] decimals = format[0].Split('.');
                if (decimals.Length == 2)
                {
                    return(decimals[1].Length);
                }
            }

            return(2);
        }
示例#49
0
        public List <T> ParseCSVFile <T>(string filePath, ClassMap map)
        {
            if (string.IsNullOrEmpty(filePath.Trim()))
            {
                throw new Exception("File path cannot be empty");
            }

            if (map == null)
            {
                throw new Exception("ClassMap cannot be null");
            }

            TextReader reader = new StreamReader(filePath);

            var csvReader = new CsvReader(reader);

            csvReader.Configuration.RegisterClassMap(map);
            var records = csvReader.GetRecords <T>();

            return(records.ToList <T>());
        }
        public void ShouldAllowSettingOfKeyInConvention()
        {
            var model = new PersistenceModel();

            var parent = new ClassMap <Parent>();

            parent.Id(x => x.Id);
            var child = new SubclassMap <Child>();

            model.Add(parent);
            model.Add(child);
            model.Conventions.Add <SCKeyConvention>();

            var subclass = model.BuildMappings()
                           .SelectMany(x => x.Classes)
                           .First()
                           .Subclasses.First();

            subclass.Key.Columns.First().Name.ShouldEqual("xxx");
            subclass.Key.Columns.Count().ShouldEqual(1);
        }
示例#51
0
        private void ProcessInboundClass(int dataObjectIndex, ClassMap classMap, List <string> classInstances)
        {
            for (int classInstanceIndex = 0; classInstanceIndex < classInstances.Count; classInstanceIndex++)
            {
                string classInstance   = classInstances[classInstanceIndex];
                string identifierValue = classInstance.Substring(classInstance.LastIndexOf("/") + 1);
                ProcessInboundClassIdentifiers(dataObjectIndex, classMap, classInstanceIndex, identifierValue);
            }

            ClassTemplateMap classTemplateMap = _graphMap.GetClassTemplateMap(classMap.id, classMap.index);

            if (classTemplateMap != null)
            {
                List <TemplateMap> templateMaps = classTemplateMap.templateMaps;

                if (templateMaps != null && templateMaps.Count > 0)
                {
                    ProcessInboundTemplates(dataObjectIndex, classInstances, templateMaps);
                }
            }
        }
示例#52
0
        private static void AddAssociation <TAssociationAttribute>(Type type, ClassMap mapping, XElement e) where TAssociationAttribute : AbstractAssociationAttribute, new()
        {
            var ass        = new TAssociationAttribute();
            var memberName = e.GetAttributeValue <string>("Member");
            var member     = type.GetMember(memberName).FirstOrDefault();

            if (member == null)
            {
                throw new MappingException(string.Format("Invalid member:'{0}' in type '{1}'!", memberName, type.FullName));
            }
            var storage = e.GetAttributeValue <string>("Storage");

            if (storage.HasValue())
            {
                ass.Storage = storage;
            }

            ass.ThisKey  = e.GetAttributeValue <string>("ThisKey");
            ass.OtherKey = e.GetAttributeValue <string>("OtherKey");
            mapping.members.Add(member, ass);
        }
示例#53
0
        /// <summary>
        /// 注册实体到数据表的映射关系
        /// </summary>
        /// <typeparam name="TEntity"></typeparam>
        /// <param name="fnClassMap"></param>
        /// <returns></returns>
        public DbConfiguration AddClass <TEntity>(Action <ClassMap <TEntity> > fnClassMap)
        {
            Guard.NotNull(fnClassMap, "fnClassMap");
            var entityType   = typeof(TEntity);
            var entityTypeId = entityType.TypeHandle.Value;

            if (mappings.ContainsKey(entityTypeId))
            {
                throw new RepeatRegistrationException("Repeat register entity mapping for entity '" + entityType.FullName + "'.");
            }
            var map = new ClassMap <TEntity>();

            fnClassMap(map);

            var mapping = map.CreateMapping();

            AutoMapping(mapping.entityType, mapping);

            RegistyMapping(mapping);
            return(this);
        }
        public void ShouldHaveSameTableNameForUniDirectionalMapping()
        {
            var model   = new PersistenceModel();
            var leftMap = new ClassMap <Left>();

            leftMap.Id(x => x.Id);
            leftMap.HasManyToMany(x => x.Rights);

            var rightMap = new ClassMap <Right>();

            rightMap.Id(x => x.Id);

            model.Add(leftMap);
            model.Add(rightMap);

            var mappings = model.BuildMappings();

            var leftMapping = mappings.SelectMany(x => x.Classes).Where(x => x.Type == typeof(Left)).First();

            leftMapping.Collections.First().TableName.ShouldEqual("RightToLeft");
        }
        public void CreateMapping()
        {
            var map = new ClassMap <Package>(Version.LUCENE_30);

            map.Key(p => p.Id);
            map.Key(p => p.Version).ConvertWith(new VersionConverter());

            map.Property(p => p.Description)
            .AnalyzeWith(new PorterStemAnalyzer(Version.LUCENE_30))
            .WithTermVector.PositionsAndOffsets();

            map.Property(p => p.DownloadCount)
            .AsNumericField()
            .WithPrecisionStep(8);

            map.Property(p => p.IconUrl).NotIndexed();

            map.Score(p => p.Score);

            map.DocumentBoost(p => p.Boost);
        }
        private IEnumerable <T> ReadWhere <T>(IDictionary <string, object> properties) where T : class
        {
            // get the type map
            ClassMap classMap = ClassMapper.GetClassMap <T>();

            // get the data to query
            IQueryable <T> data = this.GetData <T>().AsQueryable <T>();

            // return an empty enumerable if no objects in collection
            if (data.Count() == 0)
            {
                return(new T[0]);
            }

            // else build the predicates (can only be Equal or In)
            List <IPredicate> predicates = new List <IPredicate>();

            foreach (string key in properties.Keys)
            {
                PropertyMap pm = classMap.AllProperties[key];
                if (pm == null)
                {
                    throw new ArgumentException($"Failed to find property {key} on type {typeof(T)}");
                }

                object value     = properties[key];
                Type   valueType = value.GetType();

                if (pm.PropertyInfo.PropertyType.IsAssignableFrom(valueType))
                {
                    predicates.Add(PredicateBuilder.Equal <T>(key, value));
                }
                else
                {
                    predicates.Add(PredicateBuilder.In <T>(key, (IEnumerable)value));
                }
            }

            return(this.ReadWhere <T>(predicates));
        }
示例#57
0
            private void Arrange()
            {
                Mock <IMemberMap> property1 = new Mock <IMemberMap>();
                Mock <IMemberMap> property2 = new Mock <IMemberMap>();
                var properties = new List <IMemberMap>
                {
                    property1.Object,
                    property2.Object
                };

                var table = new Table
                {
                    Alias            = "y_1",
                    EntityType       = ClassMap.Object.EntityType,
                    Name             = ClassMap.Object.TableName,
                    ReferenceName    = "",
                    Identity         = ClassMap.Object.Identity,
                    ParentIdentity   = ClassMap.Object.Identity,
                    IsVirtual        = false,
                    PropertyInfo     = null,
                    ClassMapper      = ClassMap.Object,
                    LastIdentity     = Guid.Empty,
                    ParentEntityType = null
                };

                var column1 = new Column("Column1", property1.Object, null, table);
                var column2 = new Column("Column2", property2.Object, null, table);

                //Generator.Setup(g => g.GetColumnName(It.IsAny<IColumn>(), It.IsAny<bool>(), It.IsAny<bool>()))
                //    .Returns<IColumn, bool, bool>((column, alias, prefix) => column.Alias).Verifiable();
                ClassMap.SetupGet(c => c.Properties).Returns(properties).Verifiable();

                Dialect.SetupGet(d => d.OpenQuote).Returns('!').Verifiable();
                Dialect.SetupGet(d => d.CloseQuote).Returns('^').Verifiable();
                Dialect.Setup(d => d.GetCountSql(It.IsAny <string>()))
                .Returns <string>(sql => $"SELECT COUNT(*) AS {Dialect.Object.OpenQuote}Total{Dialect.Object.CloseQuote} FROM {sql}").Verifiable();

                Generator.Setup(g => g.GetTables(It.IsAny <IClassMapper>(), It.IsAny <IDictionary <string, object> >(), It.IsAny <IList <IReferenceMap> >()))
                .Returns("TableName").Verifiable();
            }
        public void SingleColumnValueFilter_NoCF_Validation_Throws_FilterException()
        {
            var map = new ClassMap()
            {
                Maps = new List <IMap>()
                {
                    new PropertyMap()
                    {
                        ColumnName = Maps.MockDomainObject.NameColumn,
                        Name       = nameof(MockDomainObject.Name),
                        Type       = typeof(MockDomainObject)
                    }
                }
            };

            var filter = new SingleColumnValueFilter <MockDomainObject>(map);

            filter.Column(x => x.Name);
            var validation = filter.ToFilterBuild();

            Assert.Throws <FilterException>(() => validation.Validate());
        }
        /// <inheritdoc />
        public Task <T> Read <T>(params IPredicate[] predicates) where T : class
        {
            ClassMap classMap = ClassMapper.GetClassMap <T>();

            // validate that all key properties are passed
            List <IPredicate> predicateList = new List <IPredicate>(predicates);

            // add discriminator predicates if necessary
            if (classMap.DiscriminatorProperties.Any())
            {
                predicateList.AddRange(classMap.GetDefaultPredicates <T>());
            }

            IEnumerable <T> results = this.ReadWhere <T>(predicateList);

            if (results.Count() > 1)
            {
                throw new ArgumentException("Expected predicates to evaluate to a single row.");
            }

            return(Task.FromResult(results.SingleOrDefault()));
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="Process"></param>
        public void FixTypes(ClassMap Process)
        {
            List <PropertyMap> Properties = Process.Properties;
            Int32  Length = Properties.Count;
            Int32  Count;
            String Current;

            for (Int32 I = 0; I < Length; I++)
            {
                Count   = 0;
                Current = Properties[I].Name;

                //Count Property
                for (Int32 J = 0; J < Length; J++)
                {
                    if (Current == Properties[J].Name)
                    {
                        Count++;
                    }
                }

                //If more then the same property is found then it was a collection
                if (Count > 1)
                {
                    Properties[I].Type = $"List<{Properties[I].Type}>";

                    for (Int32 J = I + 1; J < Properties.Count; J++)
                    {
                        if (Properties[J].Name == Current)
                        {
                            Properties.RemoveAt(J--);
                        }
                    }

                    //Update Length
                    Length = Properties.Count;
                }
            }
        }