public void PrepareDataAccessIncomePropertyConfigurations(MappingConfiguration<DataAccessIncome> configuration) { configuration.HasProperty(x => x.Id) .IsIdentity(KeyGenerator.Autoinc) .HasFieldName("id") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("Id") .IsNotNullable() .HasColumnType("integer") .HasPrecision(0) .HasScale(0); configuration.HasProperty(x => x.DealerId) .HasFieldName("dealerId") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("DealerId") .IsNotNullable() .HasColumnType("integer") .HasPrecision(0) .HasScale(0); configuration.HasProperty(x => x.Date) .HasFieldName("date") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("Date") .IsNotNullable() .HasColumnType("datetime"); configuration.HasProperty(x => x.Amount) .HasFieldName("amount") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("Amount") .IsNotNullable() .HasColumnType("decimal") .HasPrecision(18) .HasScale(2); }
public void PrepareDataAccessCountryPropertyConfigurations(MappingConfiguration<DataAccessCountry> configuration) { configuration.HasProperty(x => x.Id) .IsIdentity(KeyGenerator.Autoinc) .HasFieldName("id") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("Id") .IsNotNullable() .HasColumnType("integer") .HasPrecision(0) .HasScale(0); configuration.HasProperty(x => x.Name) .HasFieldName("name") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("Name") .IsNullable() .HasColumnType("longtext") .HasLength(0); configuration.HasProperty(x => x.Region) .HasFieldName("region") .WithDataAccessKind(DataAccessKind.ReadWrite) .ToColumn("Region") .IsNotNullable() .HasColumnType("integer") .HasPrecision(0) .HasScale(0); }
private void ParseMappings(XPathNavigator navigator) { XPathNodeIterator xpni = navigator.Select(CfgXmlHelper.SessionFactoryMappingsExpression); while (xpni.MoveNext()) { MappingConfiguration mc = new MappingConfiguration(xpni.Current); if (!mc.IsEmpty()) { // Workaround add first an assembly&resource and then only the same assembly. // the <mapping> of whole assembly is ignored (included only sigles resources) // The "ignore" log, is enough ? // Perhaps we can add some intelligence to remove single resource reference when a whole assembly is referenced //if (!mappings.Contains(mc)) //{ // mappings.Add(mc); //} //else //{ // string logMessage = "Ignored mapping -> " + mc.ToString(); // if (log.IsDebugEnabled) // log.Debug(logMessage); // if (log.IsWarnEnabled) // log.Warn(logMessage); //} // The control to prevent mappings duplication was removed since the engine do the right thing // for this issue (simple is better) mappings.Add(mc); } } }
protected override void TestFixtureSetUp() { base.TestFixtureSetUp(); _session = Session; _session.CreateKeyspace(_uniqueKsName); _session.ChangeKeyspace(_uniqueKsName); // Create necessary tables MappingConfiguration config1 = new MappingConfiguration(); config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(EntityWithTimeUuid), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(EntityWithTimeUuid))); _tableEntityWithTimeUuid = new Table<EntityWithTimeUuid>(_session, config1); _tableEntityWithTimeUuid.Create(); MappingConfiguration config2 = new MappingConfiguration(); config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(EntityWithNullableTimeUuid), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(EntityWithNullableTimeUuid))); _tableEntityWithNullableTimeUuid = new Table<EntityWithNullableTimeUuid>(_session, config2); _tableEntityWithNullableTimeUuid.Create(); _expectedTimeUuidObjectList = EntityWithTimeUuid.GetDefaultObjectList(); _expectedNullableTimeUuidObjectList = EntityWithNullableTimeUuid.GetDefaultObjectList(); _dateBefore = DateTimeOffset.Parse("2014-2-1"); _dateAfter = DateTimeOffset.Parse("2014-4-1"); }
private MappingConfiguration TeamMapping() { var mapping = new MappingConfiguration<Team>(); mapping.MapType() .ToTable("Team"); mapping.HasProperty(m => m.Id) .IsIdentity(KeyGenerator.Autoinc); mapping.HasProperty(m => m.IsOpen) .HasColumnType("bit"); mapping.HasAssociation(m => m.Owner) .IsManaged() .ToColumn("OwnerId"); mapping.HasAssociation(m => m.Things) .IsManaged() .ToColumn("TeamId"); mapping.HasAssociation(m => m.Members) .WithOpposite(t => t.Team) .IsManaged() .IsDependent() .ToColumn("TeamId"); return mapping; }
public MappingConfiguration<RentalRate> GetRentalRateClassConfiguration() { MappingConfiguration<RentalRate> configuration = new MappingConfiguration<RentalRate>(); configuration.MapType(x => new { }).WithConcurencyControl(OptimisticConcurrencyControlStrategy.Changed).ToTable("RentalRates"); return configuration; }
public void CqlClient_Timestamp() { var config = new MappingConfiguration() .Define(new Map<Song>().PartitionKey(s => s.Id).TableName("song_insert")); //Use linq to create the table var table = new Table<Song>(_session, config); table.CreateIfNotExists(); var mapper = new Mapper(_session, config); var song = new Song { Id = Guid.NewGuid(), Artist = "The Who", Title = "Substitute", ReleaseDate = DateTimeOffset.UtcNow }; //Set timestamp to 1 day ago var timestamp = DateTimeOffset.Now.Subtract(TimeSpan.FromDays(1)); mapper.Insert(song, true, CqlQueryOptions.New().SetTimestamp(timestamp)); //query for timestamp in a column of the record var cqlLowerCasePartitionKey = "SELECT WRITETIME (Artist) AS timestamp FROM " + table.Name + " WHERE Id = " + song.Id + ";"; var rows = _session.Execute(cqlLowerCasePartitionKey).GetRows().ToList(); Assert.AreEqual(1, rows.Count); var creationTimestamp = rows[0].GetValue<long>("timestamp"); Assert.NotNull(creationTimestamp); //Timestamp retrieved is in macroseconds. Converting it to milliseconds Assert.AreEqual(TypeSerializer.SinceUnixEpoch(timestamp).Ticks / 10, rows[0].GetValue<object>("timestamp")); }
/// <summary> /// Maps the ProjectItemUrlData class /// </summary> /// <param name="mappings">The LocatoinItemUrlData class mappings.</param> private void MapUrlData(IList<MappingConfiguration> mappings) { // map the Url data type var urlDataMapping = new MappingConfiguration<ProjectItemUrlData>(); urlDataMapping.MapType(p => new { }).Inheritance(InheritanceStrategy.Flat).ToTable("sf_url_data"); mappings.Add(urlDataMapping); }
protected override IList<MappingConfiguration> PrepareMapping() { List<MappingConfiguration> configurations = new List<MappingConfiguration>(); MappingConfiguration<Report> reportConfiguration = new MappingConfiguration<Report>(); reportConfiguration.MapType(x => new { ID = x.Id, Name = x.Name, Duration = x.Duration, Destination = x.Destination, ClientsCount = x.ClientsCount, TotalIncome = x.TotalIncome, TransportCompany = x.TransportCompany, TransportType = x.TransportType, GuideName = x.GuideName, ExpenseId = x.ExpenseId }).ToTable("Reports"); reportConfiguration.HasProperty(p => p.Id).IsIdentity(KeyGenerator.Autoinc); configurations.Add(reportConfiguration); return configurations; }
private MappingConfiguration<Question> CreateQuestionMapping() { MappingConfiguration<Question> questionMapping = new MappingConfiguration<Question>(); questionMapping.MapType(question => new { QuestionId = question.Id, QueryText = question.QueryText, PostedById = question.PostedById }) .ToTable("Questions"); questionMapping.HasProperty(q => q.Id).IsIdentity(); questionMapping.HasAssociation(q => q.PostedBy) .WithOpposite(u => u.CreatedQuestions) .HasConstraint((q, u) => q.PostedById == u.Id); questionMapping.HasAssociation(q => q.UsersThatVoted) .WithOpposite(u => u.VotedOnQuestions) .IsManaged() .MapJoinTable("QuestionsUsers", (q, u) => new { QuestionGuid = q.Id, UserGuid = u.Id }); questionMapping.HasAssociation(q => q.Answers) .WithOpposite(a => a.Question) .HasConstraint((q, a) => q.Id == a.QuestionId) .IsManaged(); return questionMapping; }
public void PrepareTeamPropertyConfigurations(MappingConfiguration<Team> configuration) { configuration.HasProperty(x => x.TeamId).IsIdentity().HasFieldName("_teamId").WithDataAccessKind(DataAccessKind.ReadWrite); configuration.HasProperty(x => x.TeamMembers).HasFieldName("_teamMembers").WithDataAccessKind(DataAccessKind.ReadWrite); configuration.HasProperty(x => x.TeamName).HasFieldName("_teamName").WithDataAccessKind(DataAccessKind.ReadWrite); configuration.HasProperty(x => x.IsEnabled).HasFieldName("_isEnabled").WithDataAccessKind(DataAccessKind.ReadWrite); }
public MappingConfiguration<TeamMember> GetTeamMemberClassConfiguration() { MappingConfiguration<TeamMember> configuration = new MappingConfiguration<TeamMember>(); configuration.MapType().WithDataAccessKind(DataAccessKind.ReadWrite); return configuration; }
protected override void TestFixtureSetUp() { base.TestFixtureSetUp(); _session = Session; _session.CreateKeyspace(_uniqueKsName); _session.ChangeKeyspace(_uniqueKsName); // Create necessary tables MappingConfiguration config1 = new MappingConfiguration(); config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof (EntityWithTimeUuid), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof (EntityWithTimeUuid))); _tableEntityWithTimeUuid = new Table<EntityWithTimeUuid>(_session, config1); _tableEntityWithTimeUuid.Create(); MappingConfiguration config2 = new MappingConfiguration(); config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof (EntityWithNullableTimeUuid), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof (EntityWithNullableTimeUuid))); _tableEntityWithNullableTimeUuid = new Table<EntityWithNullableTimeUuid>(_session, config2); _tableEntityWithNullableTimeUuid.Create(); _expectedTimeUuidObjectList = EntityWithTimeUuid.GetDefaultObjectList(); for (int i=0; i<_expectedTimeUuidObjectList.Count; i++) { _expectedTimeUuidObjectList[i].StringType = i.ToString(); } }
protected override IList<MappingConfiguration> PrepareMapping() { List<MappingConfiguration> configurations = new List<MappingConfiguration>(); var saleMapping = new MappingConfiguration<Sale>(); saleMapping.MapType(sale => new { ID = sale.Id, Dish = sale.Dish, Quantity = sale.Quantity, Month = sale.Month, Year = sale.Year }).ToTable("Sale"); saleMapping.HasProperty(s => s.Id).IsIdentity(); configurations.Add(saleMapping); var dishReportMapping = new MappingConfiguration<DishReport>(); dishReportMapping.MapType(report => new { Month = report.Month, DeliveredPrice = report.DeliveredPrice, SoldPrice = report.SoldPrice, Code = report.Code, }).ToTable("DishReport"); saleMapping.HasProperty(s => s.Id).IsIdentity(); configurations.Add(dishReportMapping); return configurations; }
public void PreparePositionPropertyConfigurations(MappingConfiguration<Position> configuration) { configuration.HasProperty(x => x.Id).IsIdentity(KeyGenerator.Autoinc); configuration.HasProperty(x => x.HeaderId); configuration.HasProperty(x => x.Description); configuration.HasProperty(x => x.SequenceNumber); configuration.HasProperty(x => x.DateCreated); configuration.HasProperty(x => x.DateModified); }
public void PrepareHeaderPropertyConfigurations(MappingConfiguration<Header> configuration) { configuration.HasProperty(x => x.Id); configuration.HasProperty(x => x.Title); configuration.HasProperty(x => x.IsChecked); configuration.HasProperty(x => x.Status); configuration.HasProperty(x => x.DateCreated); configuration.HasProperty(x => x.DateModified); }
public void PrepareRentalRatePropertyConfigurations(MappingConfiguration<RentalRate> configuration) { configuration.HasProperty(x => x.RentalRateID).IsIdentity(KeyGenerator.Autoinc).HasFieldName("_rentalRateID").WithDataAccessKind(DataAccessKind.ReadWrite).ToColumn("RentalRateID").IsNotNullable().HasColumnType("int").HasPrecision(0).HasScale(0); configuration.HasProperty(x => x.CategoryID).HasFieldName("_categoryID").WithDataAccessKind(DataAccessKind.ReadWrite).ToColumn("CategoryID").IsNullable().HasColumnType("int").HasPrecision(0).HasScale(0); configuration.HasProperty(x => x.Daily).HasFieldName("_daily").WithDataAccessKind(DataAccessKind.ReadWrite).ToColumn("Daily").IsNullable().HasColumnType("smallmoney").HasPrecision(0).HasScale(0); configuration.HasProperty(x => x.Weekly).HasFieldName("_weekly").WithDataAccessKind(DataAccessKind.ReadWrite).ToColumn("Weekly").IsNullable().HasColumnType("smallmoney").HasPrecision(0).HasScale(0); configuration.HasProperty(x => x.Monthly).HasFieldName("_monthly").WithDataAccessKind(DataAccessKind.ReadWrite).ToColumn("Monthly").IsNullable().HasColumnType("smallmoney").HasPrecision(0).HasScale(0); }
public void Table_Constructor_Uses_Provided_Mappings_With_Custom_TableName() { var config = new MappingConfiguration().Define(new Map<AllTypesEntity>().TableName("tbl4").Column(t => t.Int64Value, cm => cm.WithName("id1"))); var table = new Table<AllTypesEntity>(null, config, "tbl_overridden1"); Assert.AreEqual( @"SELECT BooleanValue, DateTimeValue, DecimalValue, DoubleValue, id1, IntValue, StringValue, UuidValue FROM tbl_overridden1 WHERE id1 = ?", table.Where(t => t.Int64Value == 1).ToString()); }
public MappingConfiguration<JobSchedule> GetJobScheduleClassConfiguration() { var configuration = new MappingConfiguration<JobSchedule>(); configuration.MapType(x => new { }) .WithConcurencyControl(Changed) .ToTable("js_JobSchedules"); return configuration; }
//artificial type for backing up online deletes and "executing" offline deletes private MappingConfiguration PrepareEntityDeleteConfig() { MappingConfiguration delEntityConfig = new MappingConfiguration(DeleteOperationDefinition.DeleteOperationTypeName, DeleteOperationDefinition.DeleteOperationTypeNamespace); delEntityConfig.HasArtificialPrimitiveProperty<int>(DeleteOperationDefinition.DeleteOperationId).IsIdentity(KeyGenerator.Autoinc).ToColumn(DeleteOperationDefinition.DeleteOperationId); delEntityConfig.HasArtificialPrimitiveProperty<int>(DeleteOperationDefinition.EntityToDeleteId).ToColumn(DeleteOperationDefinition.EntityToDeleteId); delEntityConfig.HasArtificialPrimitiveProperty<string>(DeleteOperationDefinition.EntityToDeleteType).ToColumn(DeleteOperationDefinition.EntityToDeleteType); return delEntityConfig; }
public MappingConfiguration<DataAccessIncome> GetDataAccessIncomeClassConfiguration() { MappingConfiguration<DataAccessIncome> configuration = new MappingConfiguration<DataAccessIncome>(); configuration.MapType(x => new { }) .WithConcurencyControl(OptimisticConcurrencyControlStrategy.Changed) .ToTable("incomes"); return configuration; }
public void PrepareDataAccessCountryAssociationConfigurations(MappingConfiguration<DataAccessCountry> configuration) { configuration.HasAssociation(x => x.DataAccessDealers) .HasFieldName("dataAccessDealers") .WithOpposite(x => x.DataAccessCountry) .ToColumn("CountryId") .HasConstraint((y, x) => x.CountryId == y.Id) .WithDataAccessKind(DataAccessKind.ReadWrite); }
public void PrepareDataAccessIncomeAssociationConfigurations(MappingConfiguration<DataAccessIncome> configuration) { configuration.HasAssociation(x => x.DataAccessDealer) .HasFieldName("dataAccessDealer") .WithOpposite(x => x.DataAccessIncomes) .ToColumn("DealerId") .HasConstraint((x, y) => x.DealerId == y.Id) .IsRequired() .WithDataAccessKind(DataAccessKind.ReadWrite); }
public void ConvertTypesUsing_Creates_Uses_MapperFactory_Instance() { var config = new MappingConfiguration(); var originalMapperFactory = config.MapperFactory; //the mapper factory remains the same Assert.AreSame(originalMapperFactory, config.MapperFactory); config.ConvertTypesUsing(new DefaultTypeConverter()); //New instance of the mapper factory Assert.AreNotSame(originalMapperFactory, config.MapperFactory); }
public void Table_Constructor_Uses_Provided_Mappings() { var table = new Table<AllTypesEntity>(null); Assert.AreEqual( @"SELECT BooleanValue, DateTimeValue, DecimalValue, DoubleValue, Int64Value, IntValue, StringValue, UuidValue FROM AllTypesEntity", table.ToString()); var config = new MappingConfiguration().Define(new Map<AllTypesEntity>().TableName("tbl3")); table = new Table<AllTypesEntity>(null, config); Assert.AreEqual(@"SELECT BooleanValue, DateTimeValue, DecimalValue, DoubleValue, Int64Value, IntValue, StringValue, UuidValue FROM tbl3", table.ToString()); }
private void ParseMappings(XPathNavigator navigator) { XPathNodeIterator xpni = navigator.Select(CfgXmlHelper.SessionFactoryMappingsExpression); while (xpni.MoveNext()) { var mc = new MappingConfiguration(xpni.Current); if (!mc.IsEmpty()) { Mappings.Add(mc); } } }
/// <summary> /// Maps the file data. /// </summary> /// <param name="mappings">The mappings.</param> private void MapFileData(List<MappingConfiguration> mappings) { var fileDataMapping = new MappingConfiguration<FileData>(); fileDataMapping.MapType(p => new { }).WithConcurencyControl(OptimisticConcurrencyControlStrategy.None).ToTable("sf_files_monitor_data"); fileDataMapping.HasProperty(p => p.Id).IsIdentity(); fileDataMapping.HasProperty(p => p.FileName).ToColumn("file_name"); fileDataMapping.HasProperty(p => p.FilePath).ToColumn("file_path"); fileDataMapping.HasProperty(p => p.PackageName).ToColumn("package_name"); mappings.Add(fileDataMapping); }
private MappingConfiguration<IdentityRole> CreateIdentityRoleMapping() { MappingConfiguration<IdentityRole> identityRoleMapping = new MappingConfiguration<IdentityRole>(); identityRoleMapping.MapType(role => new { id = role.Id, Name = role.Name }).ToTable("IdentityRoles"); identityRoleMapping.HasProperty(x => x.Id).IsIdentity(); return identityRoleMapping; }
private MappingConfiguration<IdentityUser> CraeteIdentityUserMapping() { MappingConfiguration<IdentityUser> identityUserMapping = new MappingConfiguration<IdentityUser>(); identityUserMapping.MapType(user => new { Id = user.Id, Name = user.UserName, PasswordHash = user.PasswordHash }).ToTable("IdentityUsers"); identityUserMapping.HasProperty(x => x.Id).IsIdentity(); return identityUserMapping; }
public void CqlClientConfiguration_UseIndividualMappingClassType_StaticMappingClass() { var config = new MappingConfiguration().Define(new ManyDataTypesPocoMappingCaseSensitive()); var table = new Table<ManyDataTypesPoco>(_session, config); table.Create(); var mapper = new Mapper(_session, config); ManyDataTypesPoco manyTypesInstance = ManyDataTypesPoco.GetRandomInstance(); mapper.Insert(manyTypesInstance); string cqlSelect = string.Format("SELECT * from \"{0}\" where \"{1}\"='{2}'", table.Name, "StringType", manyTypesInstance.StringType); ManyDataTypesPoco.KeepTryingSelectAndAssert(mapper, cqlSelect, new List<ManyDataTypesPoco>() { manyTypesInstance }); }
private static void ConfigureMapping(MappingConfiguration config) { config.FluentMappings //.Conventions.AddFromAssemblyOf<IndexNameConvention>() .AddFromAssemblyOf <SessionFactoryFactory>(); }
public BusinessService() { this.UnitOfWork = new UnitOfWork(); this.Mapper = MappingConfiguration.ConfigureMapper().CreateMapper(); }
public void Should_ReturnCorrectValue_When_EmptyColumnNameAndSchemaParserV2() { using (var simulacronCluster = SimulacronCluster.CreateNew(3)) { simulacronCluster.Prime(new { when = new { query = "SELECT * FROM system_schema.tables WHERE table_name='testtable' AND keyspace_name='testks'" }, then = new { result = "success", delay_in_ms = 0, rows = new[] { new { compression = new { }, compaction = new { }, bloom_filter_fp_chance = 0.1, caching = new { keys = "ALL", rows_per_partition = "NONE" }, comment = "comment", gc_grace_seconds = 60000, dclocal_read_repair_chance = 0.1, read_repair_chance = 0.1, keyspace_name = "testks" } }, column_types = new { compression = "map<ascii, ascii>", compaction = "map<ascii, ascii>", bloom_filter_fp_chance = "double", caching = "map<ascii, ascii>", comment = "ascii", gc_grace_seconds = "int", dclocal_read_repair_chance = "double", read_repair_chance = "double", keyspace_name = "ascii" }, ignore_on_prepare = false } }); simulacronCluster.Prime(new { when = new { query = "SELECT * FROM system_schema.keyspaces" }, then = new { result = "success", delay_in_ms = 0, rows = new[] { new { replication = new { @class = "SimpleStrategy", replication_factor = "1" }, keyspace_name = "testks", durable_writes = true } }, column_types = new { replication = "map<ascii, ascii>", keyspace_name = "ascii", durable_writes = "boolean" }, ignore_on_prepare = false } }); simulacronCluster.Prime(new { when = new { query = "SELECT * FROM system_schema.indexes WHERE table_name='testtable' AND keyspace_name='testks'" }, then = new { result = "success", delay_in_ms = 0, rows = new[] { new { keyspace_name = "ascii", table_name = "ascii", index_name = "ascii", kind = "ascii", options = new { target = "Custom" } } }, column_types = new { keyspace_name = "ascii", table_name = "ascii", index_name = "ascii", kind = "ascii", options = "map<ascii,ascii>" }, ignore_on_prepare = false } }); simulacronCluster.Prime(new { when = new { query = "SELECT * FROM system_schema.columns WHERE table_name='testtable' AND keyspace_name='testks'" }, then = new { result = "success", delay_in_ms = 0, rows = new[] { new { keyspace_name = "testks", table_name = "testtable", column_name = "", clustering_order = "none", column_name_bytes = 0x12, kind = "partition_key", position = 0, type = "text" } }, column_types = new { keyspace_name = "ascii", table_name = "ascii", column_name = "ascii", clustering_order = "ascii", column_name_bytes = "blob", kind = "ascii", position = "int", type = "ascii" }, ignore_on_prepare = false } }); simulacronCluster.Prime(new { when = new { query = "SELECT \"\", \" \" FROM testks.testtable" }, then = new { result = "success", delay_in_ms = 0, rows = new[] { new Dictionary <string, string> { { "", "testval" }, { " ", "testval2" } } }, column_types = new Dictionary <string, string> { { "", "ascii" }, { " ", "ascii" } }, ignore_on_prepare = false } }); simulacronCluster.Prime(new { when = new { query = "SELECT \"\", \" \" FROM testks.testtable WHERE \"\" = ? AND \" \" = ?", @params = new { column1 = "testval", column2 = "testval2" }, param_types = new { column1 = "ascii", column2 = "ascii" } }, then = new { result = "success", delay_in_ms = 0, rows = new[] { new Dictionary <string, string> { { "", "testval" }, { " ", "testval2" } } }, column_types = new Dictionary <string, string> { { "", "ascii" }, { " ", "ascii" } }, ignore_on_prepare = false } }); var mapConfig = new MappingConfiguration(); mapConfig.Define( new Map <TestTable>() .KeyspaceName("testks") .TableName("testtable") .PartitionKey(u => u.TestColumn) .Column(u => u.TestColumn, cm => cm.WithName("")) .Column(u => u.TestColumn2, cm => cm.WithName(" "))); using (var cluster = EmptyColumnTests.BuildCluster(simulacronCluster)) { var session = cluster.Connect(); var testTables = new Table <TestTable>(session); var test = (from t in testTables.Execute() select t).First(); Assert.AreEqual("testval", test.TestColumn); Assert.AreEqual("testval2", test.TestColumn2); var mapper = new Mapper(session, mapConfig); test = mapper.Fetch <TestTable>().First(); Assert.AreEqual("testval", test.TestColumn); Assert.AreEqual("testval2", test.TestColumn2); var tableMetadata = session.Cluster.Metadata.GetTable("testks", "testtable"); Assert.IsNotNull(tableMetadata); var rs = session.Execute("SELECT \"\", \" \" FROM testks.testtable"); AssertRowSetContainsCorrectValues(rs); var ps = session.Prepare("SELECT \"\", \" \" FROM testks.testtable WHERE \"\" = ? AND \" \" = ?"); var bs = ps.Bind("testval", "testval2"); rs = session.Execute(bs); AssertRowSetContainsCorrectValues(rs); } } }
protected override void ConfigureMappings(MappingConfiguration cfg) { cfg.FluentMappings.AddFromAssemblyOf <CountryMap>() .Conventions.Add <SqLiteGeometryTypeConvention>(); }
protected MapperAndSessionTuple GetMappingClientAndSession(RowSet rowset, MappingConfiguration config = null) { return(GetMappingClientAndSession(() => TaskHelper.ToTask(rowset), config)); }
private static void ConfigureMappings(MappingConfiguration mappings) { mappings.FluentMappings.AddFromAssembly(typeof(NHibernateFactory).Assembly); }
public DefaultLogEventMapper(MappingConfiguration configuration) { _configuration = configuration; }
public void Dispose() { MappingConfiguration.Clear(); }
private void DefineMappings(MappingConfiguration m) { m.FluentMappings.AddFromAssemblyOf <EmployeeMap>(); }
protected IMapper GetMappingClient(Func <Task <RowSet> > getRowSetFunc, Action <string, object[]> queryCallback, MappingConfiguration config = null) { if (queryCallback == null) { //noop queryCallback = (q, p) => { }; } var sessionMock = new Mock <ISession>(MockBehavior.Strict); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny <BoundStatement>())) .Returns(getRowSetFunc) .Callback <BoundStatement>(s => queryCallback(s.PreparedStatement.Cql, s.QueryValues)) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny <string>())) .Returns <string>(q => TaskHelper.ToTask(GetPrepared(q))) .Verifiable(); return(GetMappingClient(sessionMock, config)); }
protected override void DefineMappings(MappingConfiguration m) { m.FluentMappings.AddFromAssemblyOf <EmployeeMap>(); }
protected IMapper GetMappingClient(Func <Task <RowSet> > getRowSetFunc, MappingConfiguration config = null) { return(GetMappingClient(getRowSetFunc, null, config)); }
protected IMapper GetMappingClient(RowSet rowset, MappingConfiguration config = null) { return(GetMappingClient(() => TaskHelper.ToTask(rowset), config)); }
public void CqlClient_TwoInstancesBasedOnSameSession() { // Setup MappingConfiguration config1 = new MappingConfiguration(); config1.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(Poco1), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(Poco1))); var table1 = new Table <Poco1>(_session, config1); table1.Create(); string cqlSelectAll1 = "SELECT * from " + table1.Name; MappingConfiguration config2 = new MappingConfiguration(); config2.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(Poco2), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(Poco2))); var table2 = new Table <Poco2>(_session, config2); table2.Create(); string cqlSelectAll2 = "SELECT * from " + table2.Name; // Now re-instantiate the cqlClient, but with mapping rule that resolves the missing key issue var cqlClient1 = new Mapper(_session, new MappingConfiguration().Define(new Poco1Mapping())); var cqlClient2 = new Mapper(_session, new MappingConfiguration().Define(new Poco2Mapping())); // insert new record into two separate tables Poco1 poco1 = new Poco1(); poco1.SomeString1 += "1"; cqlClient1.Insert(poco1); Poco2 poco2 = new Poco2(); poco2.SomeString2 += "1"; cqlClient2.Insert(poco2); // Select Values from each table List <Poco1> poco1s = cqlClient1.Fetch <Poco1>(cqlSelectAll1).ToList(); Assert.AreEqual(1, poco1s.Count); Assert.AreEqual(poco1.SomeString1, poco1s[0].SomeString1); Assert.AreEqual(poco1.SomeDouble1, poco1s[0].SomeDouble1); List <Poco2> poco2s = cqlClient2.Fetch <Poco2>(cqlSelectAll2).ToList(); Assert.AreEqual(1, poco2s.Count); Assert.AreEqual(poco2.SomeString2, poco2s[0].SomeString2); Assert.AreEqual(poco2.SomeDouble2, poco2s[0].SomeDouble2); // Try that again poco1s.Clear(); Assert.AreEqual(0, poco1s.Count); poco1s = cqlClient1.Fetch <Poco1>(cqlSelectAll1).ToList(); Assert.AreEqual(1, poco1s.Count); Assert.AreEqual(poco1.SomeString1, poco1s[0].SomeString1); Assert.AreEqual(poco1.SomeDouble1, poco1s[0].SomeDouble1); poco2s.Clear(); Assert.AreEqual(0, poco2s.Count); poco2s = cqlClient1.Fetch <Poco2>(cqlSelectAll2).ToList(); Assert.AreEqual(1, poco2s.Count); Assert.AreEqual(poco2.SomeString2, poco2s[0].SomeString2); Assert.AreEqual(poco2.SomeDouble2, poco2s[0].SomeDouble2); }
public IMappingsStorage Create(MappingConfiguration mappingConfiguration) { return(new MappingsStorage(mappingConfiguration)); }
internal static void Mapping(MappingConfiguration mapping) { mapping.FluentMappings.AddFromAssemblyOf <MapeamentoTitulo>() .Conventions.AddFromAssemblyOf <ConvencaoPrimaryKey>() .Conventions.AddFromAssemblyOf <ConvencaoForeignKey>(); }
public void CleanupControllerBase() { NinjectWebCommon.Stop(); MappingConfiguration.Stop(); }
public void LinqWhere_AppendMultipleTimes() { int userId = 1; int date = 2; long time = 3; var config = new MappingConfiguration(); config.MapperFactory.PocoDataFactory.AddDefinitionDefault(typeof(TestTable), () => LinqAttributeBasedTypeDefinition.DetermineAttributes(typeof(TestTable))); var table = new Table <TestTable>(Session, config); var data = new List <TestTable> { new TestTable { UserId = 1, Date = 2, TimeColumn = 1 }, new TestTable { UserId = 1, Date = 2, TimeColumn = 2 }, new TestTable { UserId = 1, Date = 2, TimeColumn = 3 }, new TestTable { UserId = 1, Date = 2, TimeColumn = 4 }, new TestTable { UserId = 1, Date = 2, TimeColumn = 5 } }; TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT \"date\", \"time\", \"user\" FROM \"{TestTable.TableName}\" " + "WHERE \"user\" = ? AND \"date\" = ? ALLOW FILTERING", rows => rows.WithParams(userId, date)) .ThenRowsSuccess( new [] { "date", "time", "user" }, rows => rows.WithRows(data.Select( t => new object [] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT \"date\", \"time\", \"user\" FROM \"{TestTable.TableName}\" " + "WHERE \"user\" = ? AND \"date\" = ? AND \"time\" >= ? ORDER BY \"time\" ALLOW FILTERING", rows => rows.WithParams(userId, date, time)) .ThenRowsSuccess( new [] { "date", "time", "user" }, rows => rows.WithRows(data.Where(t => t.TimeColumn >= time).OrderBy(t => t.TimeColumn).Select( t => new object [] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); TestCluster.PrimeFluent( b => b.WhenQuery( $"SELECT \"date\", \"time\", \"user\" FROM \"{TestTable.TableName}\" " + "WHERE \"user\" = ? AND \"date\" = ? AND \"time\" <= ? ORDER BY \"time\" DESC ALLOW FILTERING", rows => rows.WithParams(userId, date, time)) .ThenRowsSuccess( new [] { "date", "time", "user" }, rows => rows.WithRows(data.Where(t => t.TimeColumn <= time).OrderByDescending(t => t.TimeColumn).Select( t => new object [] { t.Date, t.TimeColumn, t.UserId }).ToArray()))); var query1Actual = table.Where(i => i.UserId == userId && i.Date == date); var query2Actual = query1Actual.Where(i => i.TimeColumn >= time); query2Actual = query2Actual.OrderBy(i => i.TimeColumn); // ascending var query3Actual = query1Actual.Where(i => i.TimeColumn <= time); query3Actual = query3Actual.OrderByDescending(i => i.TimeColumn); var query1Expected = "SELECT \"date\", \"time\", \"user\" FROM \"test1\" WHERE \"user\" = ? AND \"date\" = ? ALLOW FILTERING"; var query2Expected = "SELECT \"date\", \"time\", \"user\" FROM \"test1\" WHERE \"user\" = ? AND \"date\" = ? AND \"time\" >= ? ORDER BY \"time\" ALLOW FILTERING"; var query3Expected = "SELECT \"date\", \"time\", \"user\" FROM \"test1\" WHERE \"user\" = ? AND \"date\" = ? AND \"time\" <= ? ORDER BY \"time\" DESC ALLOW FILTERING"; Assert.AreEqual(query1Expected, query1Actual.ToString()); Assert.AreEqual(query2Expected, query2Actual.ToString()); Assert.AreEqual(query3Expected, query3Actual.ToString()); var result2Actual = query2Actual.Execute().ToList(); var result3Actual = query3Actual.Execute().ToList(); Assert.AreEqual(3, result2Actual.First().TimeColumn); Assert.AreEqual(5, result2Actual.Last().TimeColumn); Assert.AreEqual(3, result3Actual.First().TimeColumn); Assert.AreEqual(1, result3Actual.Last().TimeColumn); }
public void Apply(MappingConfiguration configuration) { configuration.FluentMappings.AddFromAssembly(_assembly); }
public void AddMappings(MappingConfiguration configuration) { MappingContributors.Each(x => x.Apply(configuration)); }
public void LinqAttributes_Counter_Increments(int increment) { // Create config that uses linq based attributes var mappingConfig = new MappingConfiguration(); var counterTable = new Table <CounterEntityWithLinqAttributes>(_session, mappingConfig); counterTable.CreateIfNotExists(); var counter = new CounterEntityWithLinqAttributes { KeyPart1 = Guid.NewGuid(), KeyPart2 = 1 }; counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); var updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2).Execute().FirstOrDefault(); Assert.AreEqual(increment, updatedCounter.Counter); counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2).Execute().FirstOrDefault(); Assert.AreEqual(increment * 2, updatedCounter.Counter); counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = increment }) .Update().Execute(); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2).Execute().FirstOrDefault(); Assert.AreEqual(increment * 3, updatedCounter.Counter); //testing negative values int negativeIncrement = -1 * increment; counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2).Execute().FirstOrDefault(); Assert.AreEqual(increment * 2, updatedCounter.Counter); counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2).Execute().FirstOrDefault(); Assert.AreEqual(increment, updatedCounter.Counter); counterTable .Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2) .Select(t => new CounterEntityWithLinqAttributes { Counter = negativeIncrement }) .Update().Execute(); updatedCounter = counterTable.Where(t => t.KeyPart1 == counter.KeyPart1 && t.KeyPart2 == counter.KeyPart2).Execute().FirstOrDefault(); Assert.AreEqual(0, updatedCounter.Counter); }
protected override void ConfigMappings(MappingConfiguration mapConfig) { mapConfig.FluentMappings .Add <DBUserInfoMap>(); }
protected MapperAndSessionTuple GetMappingClientAndSession(Func <Task <RowSet> > getRowSetFunc, MappingConfiguration config = null) { return(GetMappingClientAndSession(getRowSetFunc, null, config)); }
public Connection(ICluster cluster, ISession session, MappingConfiguration mapConfig) { this.cluster = cluster; this.Session = session; this.Mapper = new Mapper(this.Session, mapConfig); }
protected IMapper GetMappingClient(Func <Task <RowSet> > getRowSetFunc, Action <string, object[]> queryCallback, MappingConfiguration config = null) { return(GetMappingClientAndSession(getRowSetFunc, queryCallback, config).Mapper); }
public void Apply(MappingConfiguration configuration) { new FluentMappingFromAssembly().WithAssembly(typeof(PersonalPlanungsMappings).Assembly.CodeBase).ApplyMappings(configuration); }
public BusinessService(IUnitOfWork uow) { UnitOfWork = uow ?? throw new NullReferenceException(); Mapper = MappingConfiguration.ConfigureMapper().CreateMapper(); }
public void Insert_Batch_With_Options() { var anotherKeyspace = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant(); using (var cluster = Cluster.Builder().AddContactPoint(TestCluster.InitialContactPoint) .WithSocketOptions(new SocketOptions().SetConnectTimeoutMillis(30000)) .Build()) { var session = cluster.Connect(); session.CreateKeyspace(anotherKeyspace, new Dictionary <string, string> { { "class", "SimpleStrategy" }, { "replication_factor", "3" } }); session.ChangeKeyspace(anotherKeyspace); var config = new MappingConfiguration().Define(new Map <PlainUser>() .ExplicitColumns() .PartitionKey(s => s.UserId) .Column(s => s.FavoriteColor, c => c.WithDbType <int>()) .Column(s => s.Name) .Column(s => s.UserId, c => c.WithName("id")) .TableName("batch_with_options_table")); //Use linq to create the table new Table <PlainUser>(session, config).CreateIfNotExists(); var mapper = new Mapper(session, config); var user1 = new PlainUser { UserId = Guid.NewGuid(), Name = "My user", FavoriteColor = RainbowColor.Orange }; var user2 = new PlainUser { UserId = Guid.NewGuid(), Name = "My user 2", FavoriteColor = RainbowColor.Blue }; var user3 = new PlainUser { UserId = Guid.NewGuid(), Name = "My user 3", FavoriteColor = RainbowColor.Blue }; var batch = mapper.CreateBatch(); batch.Insert(user1); batch.Insert(user2); var consistency = ConsistencyLevel.All; batch.WithOptions(o => o.SetConsistencyLevel(consistency)); //Timestamp for BATCH request is supported in Cassandra 2.1 or above. if (TestClusterManager.CassandraVersion > Version.Parse("2.1")) { var timestamp = DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(1)); batch.WithOptions(o => o.SetTimestamp(timestamp)); } var ex = Assert.Throws <UnavailableException>(() => mapper.Execute(batch)); Assert.AreEqual(ConsistencyLevel.All, ex.Consistency, "Consistency level of batch exception should be the same as specified at CqlQueryOptions: ALL"); Assert.AreEqual(3, ex.RequiredReplicas); Assert.AreEqual(1, ex.AliveReplicas); } }
public void Update_Poco_With_Enum_Collections_Test() { var expectedCollection = new[] { HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary <HairColor, TimeUuid> { { HairColor.Brown, TimeUuid.NewId() }, { HairColor.Red, TimeUuid.NewId() } }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = new SortedDictionary <int, Guid>(expectedMap.ToDictionary(kv => (int)kv.Key, kv => (Guid)kv.Value)); var pocoToUpdate = new PocoWithEnumCollections { Id = 3000L, Dictionary1 = expectedMap.ToDictionary(x => x.Key, x => x.Value), Dictionary2 = expectedMap.ToDictionary(x => x.Key, x => x.Value), Dictionary3 = expectedMap, List1 = expectedCollection.ToList(), List2 = expectedCollection.ToList(), Set1 = new SortedSet <HairColor>(expectedCollection), Set2 = new SortedSet <HairColor>(expectedCollection), Set3 = new HashSet <HairColor>(expectedCollection) }; pocoToUpdate.Array1 = new[] { HairColor.Blonde, HairColor.Red, HairColor.Black }; pocoToUpdate.Dictionary1.Add(HairColor.Black, Guid.NewGuid()); pocoToUpdate.Dictionary2.Add(HairColor.Black, Guid.NewGuid()); pocoToUpdate.List1.Add(HairColor.Black); pocoToUpdate.Set1.Add(HairColor.Black); pocoToUpdate.Set2.Add(HairColor.Black); pocoToUpdate.Set3.Add(HairColor.Black); const string insertQuery = "INSERT INTO tbl_with_enum_collections (id, list1, list2, array1, set1, set2, set3, map1, map2, map3)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; _session.Execute(new SimpleStatement(insertQuery, pocoToUpdate.Id, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, mapValues, mapValues, mapValues)); var config = new MappingConfiguration().Define( PocoWithEnumCollections.DefaultMapping.TableName("tbl_with_enum_collections")); var mapper = new Mapper(_session, config); mapper.Update(pocoToUpdate); var statement = new SimpleStatement("SELECT * FROM tbl_with_enum_collections WHERE id = ?", pocoToUpdate.Id); var row = _session.Execute(statement).First(); Assert.AreEqual(pocoToUpdate.Id, row.GetValue <long>("id")); CollectionAssert.AreEquivalent(pocoToUpdate.List1.Select(x => (int)x).ToList(), row.GetValue <IEnumerable <int> >("list1")); CollectionAssert.AreEquivalent(pocoToUpdate.List2.Select(x => (int)x).ToList(), row.GetValue <IEnumerable <int> >("list2")); CollectionAssert.AreEquivalent(pocoToUpdate.Array1.Select(x => (int)x).ToArray(), row.GetValue <IEnumerable <int> >("array1")); CollectionAssert.AreEquivalent(pocoToUpdate.Set1.Select(x => (int)x), row.GetValue <IEnumerable <int> >("set1")); CollectionAssert.AreEquivalent(pocoToUpdate.Set2.Select(x => (int)x), row.GetValue <IEnumerable <int> >("set2")); CollectionAssert.AreEquivalent(pocoToUpdate.Set3.Select(x => (int)x), row.GetValue <IEnumerable <int> >("set3")); CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary1.ToDictionary(x => (int)x.Key, x => (Guid)x.Value), row.GetValue <IDictionary <int, Guid> >("map1")); CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary2.ToDictionary(x => (int)x.Key, x => (Guid)x.Value), row.GetValue <IDictionary <int, Guid> >("map2")); CollectionAssert.AreEquivalent(pocoToUpdate.Dictionary3.ToDictionary(x => (int)x.Key, x => (Guid)x.Value), row.GetValue <IDictionary <int, Guid> >("map3")); }
private void Mapping(MappingConfiguration mapping) { }