Ejemplo n.º 1
0
 public void AutoMapUnspecifiedTargets()
 {
     //automap should always automap:
     var map = new AutoMap<User, UserModel>();
     map.AutoMapUnspecifiedTargets = false;
     Assert.AreEqual(true, map.AutoMapUnspecifiedTargets);
 }
Ejemplo n.º 2
0
 public void AutoMap_Create_ClassSource()
 {
     var map = new AutoMap<User, UserModel>()
                     .Specify(s => s.Address.Line1, t => t.AddressLine1);
     var user = GetFullUser();
     UserModel partial = map.Create(user);
     AssertEqual(user, partial);
 }
        public void CanGetTheManyToManyPart()
        {
            var propertyInfo = ReflectionHelper.GetProperty<ManyToMany1>(x => x.Many1);
            var autoMap = new AutoMap<ManyToMany1>();

            var mapper = new ManyToManyAutoMapper(new AutoMappingExpressions());
            object manyToManyPart = mapper.GetManyToManyPart<ManyToMany1>(autoMap, propertyInfo);

            manyToManyPart.ShouldBeOfType(typeof(ManyToManyPart<ManyToMany2>));
        }
        public void CanMapManyToManyProperty()
        {
            var propertyInfo = ReflectionHelper.GetProperty<ManyToMany1>(x => x.Many1);
            var autoMap = new AutoMap<ManyToMany1>();

            var mapper = new ManyToManyAutoMapper(new AutoMappingExpressions());
            mapper.Map<ManyToMany1>(autoMap, propertyInfo);

            autoMap.PropertiesMapped.ShouldHaveCount(1);
        }
Ejemplo n.º 5
0
        private AutoPersistenceModel Generate()
        {
            AutoPersistenceModel mappings = AutoMap.Assembly(this.GetType().Assembly, new AutoMapConfiguration());

            mappings.Conventions.Setup(finder =>
            {
                finder.Add <EnumConvention>();
            });
            mappings.UseOverridesFromAssembly(GetType().Assembly);
            return(mappings);
        }
        public AutoPersistenceModel Generate()
        {
            var mappings = AutoMap.AssemblyOf <MyEntity1>(new AutomappingConfiguration());

            mappings.IgnoreBase <Entity>();
            mappings.IgnoreBase(typeof(EntityWithTypedId <>));
            mappings.Conventions.Setup(GetConventions());
            mappings.UseOverridesFromAssemblyOf <AutoPersistenceModelGenerator>();

            return(mappings);
        }
Ejemplo n.º 7
0
        public void Add(GroupDTO group)
        {
            if (group == null)
            {
                throw new ValidationException("Группа не найдена.", "");
            }
            var addingGroup = AutoMap <GroupDTO, Group> .Map(group);

            Database.Groups.Add(addingGroup);
            Database.Commit();
        }
        public static void Run()
        {
            Configuration   cfg     = null;
            ISessionFactory factory = null;

            try
            {
                #region NHibernate initialize

                var mapCfg = new AutoMappingConfig();

                /*
                 * When Automap is being used system does not know which namespaces to investigate under certain assembly.
                 * This configuration helps FluentNHibernate to seach proper namespaces or else.
                 * This can be modified accordign to needs.
                 *
                 * Always prefer writing you own mapping files.
                 */
                factory = Fluently.Configure()
                          .Database(MsSqlConfiguration.MsSql2008
                                    .ConnectionString(c => c
                                                      .FromConnectionStringWithKey("Connection"))
                                    .ShowSql())
                          .Mappings(m => m
                                    .AutoMappings.Add(
                                        AutoMap.AssemblyOf <Customer>(mapCfg)))
                          .BuildSessionFactory();


                #endregion

                Random randomGenerator = new Random();
                int    random          = randomGenerator.Next((int)(DateTime.Now.Ticks % (long)int.MaxValue));


                using (var session = factory.OpenSession())
                    using (var transaction = session.BeginTransaction())
                    {
                        Customer customer = new Customer();
                        customer.Name      = "Barış_" + random.ToString();
                        customer.SurName   = "Akan_" + random.ToString();
                        customer.EMail     = "bakan" + random.ToString() + "@innova.com.tr";
                        customer.BirthDate = DateTime.Today;

                        session.Save(customer);
                        transaction.Commit();
                        session.Close();
                    }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 9
0
        public void SubclassOverrideShouldOverrideExistingHasManyToMany()
        {
            var autoMapper = AutoMap.AssemblyOf <ExampleClass>()
                             .Where(t => t.Namespace == "FluentNHibernate.Automapping.TestFixtures")
                             .Setup(x => x.SubclassStrategy = type => SubclassStrategy.Subclass)
                             .Override <ExampleInheritedClass>(m => m.HasManyToMany(x => x.Children).Inverse());

            new AutoMappingTester <ExampleClass>(autoMapper)
            .Element("//subclass/bag[@name='Children']").HasAttribute("inverse", "true")
            .Element("//subclass/bag[@name='Children']/many-to-many").Exists();
        }
Ejemplo n.º 10
0
        public void TestDoNotAddJoinedSubclassesForConcreteBaseTypes()
        {
            var autoMapper = AutoMap.AssemblyOf <ExampleClass>()
                             .Where(t => t.Namespace == "FluentNHibernate.Automapping.TestFixtures")
                             .Setup(c =>
                                    c.IsConcreteBaseType = b =>
                                                           b == typeof(ExampleClass));

            new AutoMappingTester <ExampleClass>(autoMapper)
            .Element("class/joined-subclass").DoesntExist();
        }
Ejemplo n.º 11
0
        public void AutoMap_Create_WithSpecify()
        {
            AutoMap <User, LegacyUser> map =
                new AutoMap <User, LegacyUser>()
                .Matching <SimpleNameMatchingStrategy>()
                .Specify(s => s.DateOfBirth, t => t.D_O_B);
            User       user    = GetFullUser();
            LegacyUser partial = map.Create(user);

            AssertEqual(user, partial);
        }
Ejemplo n.º 12
0
        public void AutoMap_Populate_ClassSource()
        {
            AutoMap <User, UserModel> map = new AutoMap <User, UserModel>().Matching <ExactNameMatchingStrategy>();

            map.Specify(s => s.Address.Line1, t => t.AddressLine1);
            User      user    = GetFullUser();
            UserModel partial = new UserModel();

            map.Populate(user, partial);
            AssertEqual(user, partial);
        }
Ejemplo n.º 13
0
        public AutoPersistenceModel Generate()
        {
            const string NamespaceToAdd = "MediaCommMVC.Web.Core.Model";

            AutoPersistenceModel autoPersistenceModel =
                AutoMap.AssemblyOf <AutoMapGenerator>().Where(
                    t => t.Namespace != null && t.Namespace.StartsWith(NamespaceToAdd, StringComparison.Ordinal)).UseOverridesFromAssemblyOf
                <AutoMapGenerator>().Conventions.AddFromAssemblyOf <AutoMapGenerator>();

            return(autoPersistenceModel);
        }
Ejemplo n.º 14
0
        public void Add(StudentDTO student)
        {
            if (student == null)
            {
                throw new ValidationException("Студент не найден", "");
            }
            Student addingStudent = AutoMap <StudentDTO, Student> .Map(student);

            Database.Students.Add(addingStudent);
            Database.Commit();
        }
Ejemplo n.º 15
0
        public AutoPersistenceModel Generate()
        {
            var mappings = AutoMap.AssemblyOf <Feed>(new AutomappingConfiguration())
                           .IgnoreBase <Entity>()
                           .IgnoreBase(typeof(EntityWithTypedId <>))
                           .UseOverridesFromAssemblyOf <AutoPersistenceModelGenerator>();

            Integrator.SetupConventions(mappings);

            return(mappings);
        }
Ejemplo n.º 16
0
        public IActionResult Add([FromBody] UserRequest userRequest)
        {
            User userEntity = AutoMap.Map <UserRequest, User>(userRequest);

            userEntity.Identity = default;
            this._userService.Add(userEntity);

            UserResponse userResponse = AutoMap.Map <UserRequest, UserResponse>(userRequest);

            return(Ok(new BaseResponse <UserResponse>(userResponse)));
        }
        public static AutoPersistenceModel GetNhibernateServicesMappings(bool registerOperationalServices, bool registerConfigurationServices)
        {
            var config = new AutomappingConfiguration(registerOperationalServices, registerConfigurationServices);

            var map = AutoMap.AssemblyOf <IBaseEntity>(config)
                      .Conventions.Add(DefaultCascade.All())
                      .UseOverridesFromAssemblyOf <IBaseEntity>()
                      .IgnoreBase(typeof(BaseEntity <>));

            return(map);
        }
Ejemplo n.º 18
0
        public IActionResult Add([FromBody] RoleRequest budgetRequest)
        {
            Role role = AutoMap.Map <RoleRequest, Role>(budgetRequest);

            role.Identity = default;
            this._roleService.Add(role);

            RoleResponse roleResponse = AutoMap.Map <RoleRequest, RoleResponse>(budgetRequest);

            return(Ok(new BaseResponse <RoleResponse>(roleResponse)));
        }
Ejemplo n.º 19
0
 public void UserToUserModel_AutoMap()
 {
     for (int i = 0; i < PerformanceIterations; i++)
     {
         User      user    = GetFullUser();
         UserModel partial = new AutoMap <User, UserModel>()
                             .Specify((s, t) => t.AddressLine1 = s.Address.Line1)
                             .Create(user);
         AssertEqual(user, partial);
     }
 }
Ejemplo n.º 20
0
 static UnitOfWork()
 {
     _sessionFactory = Fluently.Configure().Database(OracleDataClientConfiguration.Oracle10.
                                                     ConnectionString(x =>
                                                                      x.FromConnectionStringWithKey("default")).Provider <NHibernate.Connection.DriverConnectionProvider>()
                                                     .Driver <NHibernate.Driver.OracleManagedDataClientDriver>())
                       .Mappings(x => x.AutoMappings.Add(
                                     AutoMap.AssemblyOf <Student>(new AutomappingConfiguration()).UseOverridesFromAssemblyOf <StudentOverrides>()))
                       .ExposeConfiguration(config => new SchemaUpdate(config).Execute(false, true))
                       .BuildSessionFactory();
 }
Ejemplo n.º 21
0
        public void Add(SubjectDTO subject)
        {
            if (subject == null)
            {
                throw new ValidationException("Предмет не найден.", "");
            }
            var addingSubject = AutoMap <SubjectDTO, Subject> .Map(subject);

            Database.Subjects.Add(addingSubject);
            Database.Commit();
        }
Ejemplo n.º 22
0
 protected void Application_Start()
 {
     HtmlHelper.ClientValidationEnabled = true;
     SetUpDatabase();
     SetUpIoc();
     AreaRegistration.RegisterAllAreas();
     WebApiConfig.Register(GlobalConfiguration.Configuration);
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
     RouteConfig.RegisterRoutes(RouteTable.Routes);
     AutoMap.Initialize(new WebShopMappingProfile());
 }
Ejemplo n.º 23
0
        private static AutoPersistenceModel CreateInspectionAutoMappings()
        {
            var besiktningConfiguration = new InspectionConfiguration();
            var besiktningModel         =
                AutoMap
                .AssemblyOf <AssemblyToken>(besiktningConfiguration)
                .UseOverridesFromAssemblyOf <AssemblyToken>()
                .Conventions.Add(new EnumConvention());

            return(besiktningModel);
        }
Ejemplo n.º 24
0
        public void TestInheritanceSubclassOverridingMappingProperties()
        {
            var autoMapper = AutoMap.AssemblyOf <ExampleClass>()
                             .Setup(x => x.SubclassStrategy = t => SubclassStrategy.Subclass)
                             .Override <ExampleClass>(t => t.SubClass <ExampleInheritedClass>("discriminator", p => p.Map(c => c.ExampleProperty, "columnName")))
                             .Where(t => t.Namespace == "FluentNHibernate.Automapping.TestFixtures");

            new AutoMappingTester <ExampleClass>(autoMapper)
            .Element("class/subclass")
            .ChildrenDontContainAttribute("name", "LineOne");
        }
Ejemplo n.º 25
0
        public void CanSetFilterInOverride()
        {
            var model = AutoMap.Source(new StubTypeSource(new[] { typeof(Parent) }))
                        .Override <Parent>(o => o.ApplyFilter("filter1"));

            HibernateMapping hibernateMapping = model.BuildMappings().First();

            ClassMapping classMapping = hibernateMapping.Classes.First();

            classMapping.Filters.Single().Name.ShouldEqual("filter1");
        }
Ejemplo n.º 26
0
        public void SubclassOverrideShouldOverrideExistingHasOne()
        {
            var autoMapper = AutoMap.AssemblyOf <ExampleClass>()
                             .Where(t => t.Namespace == "FluentNHibernate.Automapping.TestFixtures")
                             .Setup(x => x.SubclassStrategy = type => SubclassStrategy.Subclass)
                             .Override <ExampleInheritedClass>(m => m.HasOne(x => x.Parent));

            new AutoMappingTester <ExampleClass>(autoMapper)
            .Element("//subclass/one-to-one[@name='Parent']").Exists()
            .Element("//subclass/bag[@name='Parent']").DoesntExist();
        }
        public void ShouldIgnorePropertiesInChild()
        {
            var model = AutoMap.Source(new StubTypeSource(new[] { typeof(Parent), typeof(Child), typeof(Property) }))
                        .Override <Child>(o => o.IgnoreProperty(x => x.AnotherProperty));

            var classMapping = model.BuildMappings()
                               .First()
                               .Classes.First();

            classMapping.Subclasses.First().Properties.ShouldNotContain(x => x.Name == "AnotherProperty");
        }
Ejemplo n.º 28
0
        public IActionResult Modify([FromBody] CategoryRequest categoryRequest)
        {
            Category category = AutoMap.Map <CategoryRequest, Category>(categoryRequest);

            category.Identity = default;
            this._categoryService.Modify(category.Identity, category);

            CategoryResponse categoryResponses = AutoMap.Map <CategoryRequest, CategoryResponse>(categoryRequest);

            return(Ok(new BaseResponse <CategoryResponse>(categoryResponses)));
        }
Ejemplo n.º 29
0
 /// <summary>
 /// Creates a session factory using the configurer and the action
 /// </summary>
 /// <param name="configurer">Configuration for persistence to use</param>
 /// <param name="buildSchema">Optional schema generation</param>
 /// <returns></returns>
 public static ISessionFactory CreateSessionFactory(IPersistenceConfigurer configurer,
                                                    Action <Configuration> buildSchema)
 {
     return(Fluently
            .Configure()
            .ExposeConfiguration(buildSchema)
            .ExposeConfiguration(AddProxyConfiguration)
            .Database(configurer)
            .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf <Movie>()))
            .BuildSessionFactory());
 }
Ejemplo n.º 30
0
        protected virtual AutoPersistenceModel CreateMappingModel()
        {
            var m = AutoMap.Assembly(typeof(EntityBase).Assembly)
                    .Where(IsDomainEntity)
                    .OverrideAll(ShouldIgnoreProperty)
                    .IgnoreBase <EntityBase>()
                    .IgnoreBase <EntityWithIdBase>()
                    .IgnoreBase <EntityWithDescriptionBase>();

            return(m);
        }
Ejemplo n.º 31
0
        public void UserToUserModel_AutoMap_Reused()
        {
            var map = new AutoMap <User, UserModel>();

            for (int i = 0; i < PerformanceIterations; i++)
            {
                User      user    = GetFullUser();
                UserModel partial = map.Create(user);
                AssertEqual(user, partial);
            }
        }
Ejemplo n.º 32
0
        public void Add(OffsetDTO offset)
        {
            if (offset == null)
            {
                throw new ValidationException("Оценка не найдена", "");
            }
            Offset addingOffset = AutoMap <OffsetDTO, Offset> .Map(offset);

            Database.Offsets.Add(addingOffset);
            Database.Commit();
        }
Ejemplo n.º 33
0
        public IActionResult Add([FromBody] ProductRequest productRequest)
        {
            Product product = AutoMap.Map <ProductRequest, Product>(productRequest);

            product.Identity = default;
            this._productService.Add(product);

            ProductResponse productResponse = AutoMap.Map <ProductRequest, ProductResponse>(productRequest);

            return(Ok(new BaseResponse <ProductResponse>(productResponse)));
        }
        // ManyToOneMapping referenceFromChildSecondTypeToParent;

        public override void establish_context()
        {
            var autoPersistenceModel = AutoMap.Source(new Types(), new AutomappingConfiguration());
            var hibernateMappings    = autoPersistenceModel.BuildMappings();

            var classMapping = hibernateMappings.SelectMany(h => h.Classes).Single(c => c.Type == typeof(Parent));

            collectionWithoutBackrefAndAlphabeticallyFirst = classMapping.Collections.Single(c => c.ChildType == typeof(ChildFirstType));
            collectionWithCorrespondingBackref             = classMapping.Collections.Single(c => c.ChildType == typeof(ChildSecondType));
            collectionWithoutBackrefAndAlphabeticallyLast  = classMapping.Collections.Single(c => c.ChildType == typeof(ChildThirdType));
        }
Ejemplo n.º 35
0
 public void AutoMap_Create_ClassSource_WithCache()
 {
     AutoMap<User, UserModel> map = new AutoMap<User, UserModel>().Cache<DictionaryCachingStrategy>();
     map.Specify(s => s.Address.Line1, t => t.AddressLine1);
     User user = GetFullUser();
     UserModel partial = map.Create(user);
     AssertEqual(user, partial);
     AutoMap<User, UserModel> map2 = new AutoMap<User, UserModel>().Cache<DictionaryCachingStrategy>();
     partial = map2.Create(user);
     AssertEqual(user, partial);
 }
Ejemplo n.º 36
0
 public void AutoMap_Create_WithSpecify()
 {
     AutoMap<User, LegacyUser> map = 
         new AutoMap<User, LegacyUser>()
         .Matching<SimpleNameMatchingStrategy>()
         .Specify(s => s.DateOfBirth, t => t.D_O_B);
     User user = GetFullUser();
     LegacyUser partial = map.Create(user);
     AssertEqual(user, partial);
 }
Ejemplo n.º 37
0
 public void UserThrowingExceptions()
 {
     var user = GetFullUser();
     var map = new AutoMap<User, ExceptionThrowingUser>();
     map.ThrowMappingExceptions = true;
     AssertRaisesException<MappingException>(() => map.Create(user), "MappingStrategy.DoMap failed, target: FirstName, error: The method or operation is not implemented.");
     map.ThrowMappingExceptions = false;
     var mapped = map.Create(user);
     Assert.IsNotNull(map);
     Assert.AreEqual(user.Id, mapped.Id);
 }
Ejemplo n.º 38
0
        public void AutoMap_Create_WithSpecifyAndConvert()
        {
            AutoMap<User, LegacyUser> map =
                new AutoMap<User, LegacyUser>()
                .Matching<SimpleNameMatchingStrategy>()
                .Specify<DateTime, DateTime>(s => s.DateOfBirth, t => t.D_O_B, c => c.AddDays(1));
            User user = GetFullUser();
            LegacyUser partial = map.Create(user);

            Assert.IsNotNull(partial);
            Assert.AreEqual(user.Id, partial.ID);
            Assert.AreEqual(user.FirstName, partial.First_Name);
            Assert.AreEqual(user.LastName, partial.Last_Name);
            Assert.AreEqual(user.DateOfBirth.AddDays(1), partial.D_O_B);
            Assert.AreEqual(default(DateTime), partial.Last_Modified);
        }
Ejemplo n.º 39
0
 public void UserToUserModel_AutoMap_Reused()
 {
     var map = new AutoMap<User, UserModel>();
     map.Specify((s, t) => t.AddressLine1 = s.Address.Line1);
     for (int i = 0; i < PerformanceIterations; i++)
     {
         User user = GetFullUser();
         UserModel partial = map.Create(user);
         AssertEqual(user, partial);
     }
 }
Ejemplo n.º 40
0
 public void UserToUserModel_AutoMap_Cached()
 {
     for (int i = 0; i < PerformanceIterations; i++)
     {
         User user = GetFullUser();
         UserModel partial = new AutoMap<User, UserModel>()
                                     .Specify((s, t) => t.AddressLine1 = s.Address.Line1)
                                     .Cache<DictionaryCachingStrategy>()
                                     .Create(user);
         AssertEqual(user, partial);
     }
 }
Ejemplo n.º 41
0
        public void AutoMap_Create_WithActions()
        {
            AutoMap<User, UserModel> map =
                new AutoMap<User, UserModel>()
                .Matching<SimpleNameMatchingStrategy>()
                .Specify((s, t) => t.Address.PostCode = s.Address.PostCode.Code)
                .Specify((s, t) => t.AddressLine1 = s.Address.Line1);
            User user = GetFullUser();
            
            UserModel partial = map.Create(user);

            AssertEqual(user, partial);
            Assert.AreEqual(user.Address.Line1, partial.AddressLine1);
            Assert.AreEqual(user.Address.PostCode.Code, partial.Address.PostCode);
            Assert.AreEqual(default(DateTime), partial.LastModified);
        }
Ejemplo n.º 42
0
 public void AutoMap_Populate_NoCaseMatch()
 {
     AutoMap<User, DifferentCaseUser> map = new AutoMap<User, DifferentCaseUser>().Matching<ExactNameMatchingStrategy>();
     User user = GetFullUser();
     DifferentCaseUser partial = new DifferentCaseUser();
     map.Populate(user, partial);
     AssertNotEqual(user, partial);
 }
Ejemplo n.º 43
0
 public void AutoMap_Populate_ClassSource()
 {
     AutoMap<User, UserModel> map = new AutoMap<User, UserModel>().Matching<ExactNameMatchingStrategy>();
     map.Specify(s => s.Address.Line1, t => t.AddressLine1);
     User user = GetFullUser();
     UserModel partial = new UserModel();
     map.Populate(user, partial); 
     AssertEqual(user, partial);
 }