コード例 #1
0
 private static FastCreate GetFastCreate(Type memberType, MapperCollection mapperCollection, bool isList, bool isDynamic)
 {
     return(memberType.IsAClass() || isDynamic
                ? (new FastCreate(isList
                     ? memberType.GetGenericArguments().First()
                     : memberType, mapperCollection))
                : null);
 }
コード例 #2
0
ファイル: PocoDataBuilder.cs プロジェクト: xf599/NPoco
 private static FastCreate GetFastCreate(Type memberType, MapperCollection mapperCollection, bool isList, bool isDynamic)
 {
     return(memberType.IsAClass() || isDynamic
                ? (new FastCreate(isList
                     ? (memberType.GetGenericArguments().Any() ? memberType.GetGenericArguments().First() : memberType.GetTypeWithGenericTypeDefinitionOf(typeof(IList <>)).GetGenericArguments().First())
                     : memberType, mapperCollection))
                : null);
 }
コード例 #3
0
        public SqlTemplatesBenchmark()
        {
            var mappers = new NPoco.MapperCollection();
            var factory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, mappers).Init(), mappers);

            SqlContext   = new SqlContext(new SqlServerSyntaxProvider(Options.Create(new GlobalSettings())), DatabaseType.SQLCe, factory);
            SqlTemplates = new SqlTemplates(SqlContext);
        }
コード例 #4
0
 private void ConfigurePocoDataFactoryAndMappers(IDatabase database, MapperCollection mappers)
 {
     database.Mappers = mappers;
     if (_options.PocoDataFactory != null)
     {
         database.PocoDataFactory = _cachedPocoDataFactory = (_cachedPocoDataFactory == null ? _options.PocoDataFactory.Config(mappers) : _cachedPocoDataFactory);
     }
 }
コード例 #5
0
        public static Func <object, object> GetConverter(MapperCollection mapper, PocoColumn pc, Type srcType, Type dstType)
        {
            Func <object, object> converter = null;

            // Get converter from the mapper
            if (mapper != null)
            {
                converter = pc != null && pc.MemberInfoData != null?mapper.Find(x => x.GetFromDbConverter(pc.MemberInfoData.MemberInfo, srcType)) : mapper.Find(x => x.GetFromDbConverter(dstType, srcType));

                if (converter != null)
                {
                    return(converter);
                }
            }

            if (pc != null && pc.SerializedColumn)
            {
                converter = delegate(object src)
                {
                    return(DatabaseFactory.ColumnSerializer.Deserialize((string)src, dstType));
                };
                return(converter);
            }

            // Standard DateTime->Utc mapper
            if (pc != null && pc.ForceToUtc && srcType == typeof(DateTime) && (dstType == typeof(DateTime) || dstType == typeof(DateTime?)))
            {
                converter = delegate(object src) { return(new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc)); };
                return(converter);
            }

            // Forced type conversion including integral types -> enum
            var underlyingType = UnderlyingTypes.Get(dstType, () => Nullable.GetUnderlyingType(dstType));

            if (dstType.GetTypeInfo().IsEnum || (underlyingType != null && underlyingType.GetTypeInfo().IsEnum))
            {
                if (srcType == typeof(string))
                {
                    converter = src => EnumMapper.EnumFromString((underlyingType ?? dstType), (string)src);
                    return(converter);
                }

                if (IsIntegralType(srcType))
                {
                    converter = src => Enum.ToObject((underlyingType ?? dstType), src);
                    return(converter);
                }
            }
            else if (srcType == typeof(string) && (dstType == typeof(Guid) || dstType == typeof(Guid?)))
            {
                converter = src => Guid.Parse((string)src);
            }
            else if ((!pc?.ValueObjectColumn ?? true) && !dstType.IsAssignableFrom(srcType))
            {
                converter = src => Convert.ChangeType(src, (underlyingType ?? dstType), null);
            }
            return(converter);
        }
コード例 #6
0
        public SqlTemplatesBenchmark()
        {
            var mappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var factory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, mappers).Init());

            SqlContext   = new SqlContext(new SqlCeSyntaxProvider(), DatabaseType.SQLCe, factory);
            SqlTemplates = new SqlTemplates(SqlContext);
        }
コード例 #7
0
        private MapperCollection BuildMapperCollection(IDatabase database)
        {
            var mc = new MapperCollection();

            mc.AddRange(database.Mappers);
            mc.AddRange(_options.Mapper);

            foreach (var factory in _options.Mapper.Factories)
            {
                mc.Factories[factory.Key] = factory.Value;
            }

            return(mc);
        }
コード例 #8
0
        public virtual void Setup()
        {
            this.UmbracoDatabaseMock = new Mock <IUmbracoDatabase>();

            var sqlSyntaxMock = new Mock <ISqlSyntaxProvider>();

            sqlSyntaxMock.Setup(x => x.GetQuotedTableName(It.IsAny <string>())).Returns((string x) => x);
            sqlSyntaxMock.Setup(x => x.GetQuotedColumnName(It.IsAny <string>())).Returns((string x) => x);

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());

            this.TransactionMock = new Mock <ITransaction>();

            this.UmbracoDatabaseMock.Setup(x => x.GetTransaction()).Returns(this.TransactionMock.Object);

            var sqlContextMock = new Mock <ISqlContext>();

            sqlContextMock.SetupGet(x => x.SqlSyntax).Returns(sqlSyntaxMock.Object);
            sqlContextMock.SetupGet(x => x.PocoDataFactory).Returns(pocoDataFactory);

            this.ScopeMock = new Mock <IScope>();
            this.ScopeMock.SetupGet(x => x.Database).Returns(this.UmbracoDatabaseMock.Object);
            this.ScopeMock.Setup(x => x.Complete());
            this.ScopeMock.SetupGet(x => x.SqlContext).Returns(sqlContextMock.Object);

            this.ScopeProviderMock = new Mock <IScopeProvider>();



            this.ScopeProviderMock
            .Setup(
                x => x.CreateScope(
                    IsolationLevel.Unspecified,
                    RepositoryCacheMode.Unspecified,
                    null,
                    null,
                    false,
                    true)).Returns(this.ScopeMock.Object);



            this.Repository = new NexuRelationRepository(this.ScopeProviderMock.Object);
        }
コード例 #9
0
        public virtual void Initialize()
        {
            Current.Reset();

            var container = RegisterFactory.Create();

            var ioHelper   = IOHelper.Default;
            var logger     = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>());
            var typeFinder = new TypeFinder(Mock.Of <ILogger>());
            var typeLoader = new TypeLoader(ioHelper, typeFinder, NoAppCache.Instance,
                                            new DirectoryInfo(ioHelper.MapPath("~/App_Data/TEMP")),
                                            logger,
                                            false);

            var composition = new Composition(container, typeLoader, Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run));

            composition.RegisterUnique <ILogger>(_ => Mock.Of <ILogger>());
            composition.RegisterUnique <IProfiler>(_ => Mock.Of <IProfiler>());

            composition.RegisterUnique(typeLoader);

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .AddCoreMappers();

            composition.RegisterUnique <ISqlContext>(_ => SqlContext);

            var factory = Current.Factory = composition.CreateFactory();

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());
            var sqlSyntax       = new SqlCeSyntaxProvider();

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, new Lazy <IMapperCollection>(() => factory.GetInstance <IMapperCollection>()));
            Mappers    = factory.GetInstance <IMapperCollection>();

            SetUp();
        }
コード例 #10
0
        public virtual void Initialize()
        {
            var services = TestHelper.GetRegister();

            var ioHelper   = TestHelper.IOHelper;
            var logger     = new ProfilingLogger(Mock.Of <ILogger <ProfilingLogger> >(), Mock.Of <IProfiler>());
            var typeFinder = TestHelper.GetTypeFinder();
            var typeLoader = new TypeLoader(typeFinder, NoAppCache.Instance,
                                            new DirectoryInfo(ioHelper.MapPath(Constants.SystemDirectories.TempData)),
                                            Mock.Of <ILogger <TypeLoader> >(),
                                            logger,
                                            false);

            var composition = new UmbracoBuilder(services, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader());


            services.AddUnique <ILogger>(_ => Mock.Of <ILogger>());
            services.AddUnique <ILoggerFactory>(_ => NullLoggerFactory.Instance);
            services.AddUnique <IProfiler>(_ => Mock.Of <IProfiler>());
            services.AddUnique(typeLoader);

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .AddCoreMappers();

            services.AddUnique <ISqlContext>(_ => SqlContext);

            var factory = Current.Factory = TestHelper.CreateServiceProvider(composition);

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());
            var sqlSyntax       = new SqlCeSyntaxProvider(Options.Create(new GlobalSettings()));

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, new Lazy <IMapperCollection>(() => factory.GetRequiredService <IMapperCollection>()));
            Mappers    = factory.GetRequiredService <IMapperCollection>();

            SetUp();
        }
コード例 #11
0
        public virtual void Setup()
        {
            IServiceCollection container  = TestHelper.GetServiceCollection();
            TypeLoader         typeLoader = TestHelper.GetMockedTypeLoader();

            var composition = new UmbracoBuilder(container, Mock.Of <IConfiguration>(), TestHelper.GetMockedTypeLoader());

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .AddCoreMappers();

            composition.Services.AddUnique(_ => SqlContext);

            IServiceProvider factory = composition.CreateServiceProvider();
            var pocoMappers          = new NPoco.MapperCollection
            {
                new NullableDateMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());
            var sqlSyntax       = new SqlServerSyntaxProvider(Options.Create(new GlobalSettings()));

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SqlServer2012, pocoDataFactory, factory.GetRequiredService <IMapperCollection>());
            Mappers    = factory.GetRequiredService <IMapperCollection>();
        }
コード例 #12
0
        public virtual void Initialize()
        {
            Current.Reset();

            var sqlSyntax = new SqlCeSyntaxProvider();

            var container = RegisterFactory.Create();

            var logger     = new ProfilingLogger(Mock.Of <ILogger>(), Mock.Of <IProfiler>());
            var typeLoader = new TypeLoader(NullCacheProvider.Instance,
                                            LocalTempStorage.Default,
                                            logger,
                                            false);

            var composition = new Composition(container, typeLoader, Mock.Of <IProfilingLogger>(), ComponentTests.MockRuntimeState(RuntimeLevel.Run));

            composition.RegisterUnique <ILogger>(_ => Mock.Of <ILogger>());
            composition.RegisterUnique <IProfiler>(_ => Mock.Of <IProfiler>());

            composition.RegisterUnique(typeLoader);

            composition.WithCollectionBuilder <MapperCollectionBuilder>()
            .Add(() => composition.TypeLoader.GetAssignedMapperTypes());

            var factory = Current.Factory = composition.CreateFactory();

            Mappers = factory.GetInstance <IMapperCollection>();

            var pocoMappers = new NPoco.MapperCollection {
                new PocoMapper()
            };
            var pocoDataFactory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, pocoMappers).Init());

            SqlContext = new SqlContext(sqlSyntax, DatabaseType.SQLCe, pocoDataFactory, Mappers);

            SetUp();
        }
コード例 #13
0
ファイル: PocoDataBuilder.cs プロジェクト: xf599/NPoco
 public PocoDataBuilder(Type type, MapperCollection mapper)
 {
     Type   = type;
     Mapper = mapper;
 }
コード例 #14
0
        public static PocoData ForObjectStatic(object o, string primaryKeyName, bool autoIncrement, Func <Type, PocoData> fallback, MapperCollection mapper)
        {
            var t = o.GetType();

            if (t == typeof(System.Dynamic.ExpandoObject) || t == typeof(PocoExpando))
            {
                var pd = new PocoData(t, mapper, Singleton <NullFastCreate> .Instance)
                {
                    TableInfo = new TableInfo
                    {
                        PrimaryKey    = primaryKeyName,
                        AutoIncrement = autoIncrement
                    },
                    Columns = new Dictionary <string, PocoColumn>(StringComparer.OrdinalIgnoreCase)
                };
                foreach (var col in ((IDictionary <string, object>)o))
                {
                    pd.Columns.Add(col.Key, new ExpandoColumn
                    {
                        ColumnName     = col.Key,
                        MemberInfoData = new MemberInfoData(col.Key, col.Value.GetTheType() ?? typeof(object), typeof(object)),
                    });
                }
                if (!pd.Columns.ContainsKey(primaryKeyName))
                {
                    pd.Columns.Add(primaryKeyName, new ExpandoColumn {
                        ColumnName = primaryKeyName, ColumnType = typeof(object)
                    });
                }
                return(pd);
            }
            else
            {
                return(fallback(t));
            }
        }
コード例 #15
0
 public FluentPocoDataFactory(Func <Type, IPocoDataFactory, InitializedPocoDataBuilder> resolver, MapperCollection mapperCollection)
 {
     _mapperCollection = mapperCollection;
     Resolver          = resolver;
 }
コード例 #16
0
        private SqlContext Initialize()
        {
            _logger.LogDebug("Initializing.");

            if (ConnectionString.IsNullOrWhiteSpace())
            {
                throw new InvalidOperationException("The factory has not been configured with a proper connection string.");
            }

            if (ProviderName.IsNullOrWhiteSpace())
            {
                throw new InvalidOperationException("The factory has not been configured with a proper provider name.");
            }

            if (DbProviderFactory == null)
            {
                throw new Exception($"Can't find a provider factory for provider name \"{ProviderName}\".");
            }

            _databaseType = DatabaseType.Resolve(DbProviderFactory.GetType().Name, ProviderName);
            if (_databaseType == null)
            {
                throw new Exception($"Can't find an NPoco database type for provider name \"{ProviderName}\".");
            }

            _sqlSyntax = _dbProviderFactoryCreator.GetSqlSyntaxProvider(ProviderName);
            if (_sqlSyntax == null)
            {
                throw new Exception($"Can't find a sql syntax provider for provider name \"{ProviderName}\".");
            }

            _bulkSqlInsertProvider = _dbProviderFactoryCreator.CreateBulkSqlInsertProvider(ProviderName);

            _databaseType = _sqlSyntax.GetUpdatedDatabaseType(_databaseType, ConnectionString);

            // ensure we have only 1 set of mappers, and 1 PocoDataFactory, for all database
            // so that everything NPoco is properly cached for the lifetime of the application
            _pocoMappers = new NPoco.MapperCollection();
            // add all registered mappers for NPoco
            _pocoMappers.AddRange(_npocoMappers);

            _pocoMappers.AddRange(_dbProviderFactoryCreator.ProviderSpecificMappers(ProviderName));

            var factory = new FluentPocoDataFactory(GetPocoDataFactoryResolver, _pocoMappers);

            _pocoDataFactory = factory;
            var config = new FluentConfig(xmappers => factory);

            // create the database factory
            _npocoDatabaseFactory = DatabaseFactory.Config(cfg =>
            {
                cfg.UsingDatabase(CreateDatabaseInstance) // creating UmbracoDatabase instances
                .WithFluentConfig(config);                // with proper configuration

                foreach (IProviderSpecificInterceptor interceptor in _dbProviderFactoryCreator.GetProviderSpecificInterceptors(ProviderName))
                {
                    cfg.WithInterceptor(interceptor);
                }
            });

            if (_npocoDatabaseFactory == null)
            {
                throw new NullReferenceException("The call to UmbracoDatabaseFactory.Config yielded a null UmbracoDatabaseFactory instance.");
            }

            _logger.LogDebug("Initialized.");

            return(new SqlContext(_sqlSyntax, _databaseType, _pocoDataFactory, _mappers));
        }
コード例 #17
0
        private IEnumerable <PocoMemberPlan> GetPocoMembers(MapperCollection mapper, ColumnInfo[] columnInfos, List <MemberInfo> memberInfos, string prefix = null)
        {
            var capturedMembers = memberInfos.ToArray();
            var capturedPrefix  = prefix;

            foreach (var columnInfo in columnInfos)
            {
                if (columnInfo.IgnoreColumn)
                {
                    continue;
                }

                var memberInfoType = columnInfo.MemberInfo.GetMemberInfoType();
                if (columnInfo.ReferenceType == ReferenceType.Many)
                {
                    memberInfoType = memberInfoType.GetGenericArguments().First();
                }

                var           childrenPlans      = new PocoMemberPlan[0];
                TableInfoPlan childTableInfoPlan = null;
                var           members            = new List <MemberInfo>(capturedMembers)
                {
                    columnInfo.MemberInfo
                };

                if (columnInfo.ComplexMapping || columnInfo.ReferenceType != ReferenceType.None)
                {
                    if (capturedMembers.GroupBy(x => x.GetMemberInfoType()).Any(x => x.Count() >= 2))
                    {
                        continue;
                    }

                    var childColumnInfos = GetColumnInfos(memberInfoType);

                    if (columnInfo.ReferenceType != ReferenceType.None)
                    {
                        childTableInfoPlan = GetTableInfo(memberInfoType, childColumnInfos, members);
                    }

                    var newPrefix = JoinStrings(capturedPrefix, columnInfo.ReferenceType != ReferenceType.None ? "" : (columnInfo.ComplexPrefix ?? columnInfo.MemberInfo.Name));

                    childrenPlans = GetPocoMembers(mapper, childColumnInfos, members, newPrefix).ToArray();
                }

                MemberInfo capturedMemberInfo = columnInfo.MemberInfo;
                ColumnInfo capturedColumnInfo = columnInfo;

                var accessors      = GetMemberAccessors(members);
                var memberType     = capturedMemberInfo.GetMemberInfoType();
                var isList         = IsList(capturedMemberInfo);
                var listType       = GetListType(memberType, isList);
                var isDynamic      = capturedMemberInfo.IsDynamic();
                var fastCreate     = GetFastCreate(memberType, mapper, isList, isDynamic);
                var columnName     = GetColumnName(capturedPrefix, capturedColumnInfo.ColumnName ?? capturedMemberInfo.Name);
                var memberInfoData = new MemberInfoData(capturedMemberInfo);

                yield return(tableInfo =>
                {
                    var pc = new PocoColumn
                    {
                        ReferenceType = capturedColumnInfo.ReferenceType,
                        TableInfo = tableInfo,
                        MemberInfoData = memberInfoData,
                        MemberInfoChain = members,
                        ColumnName = columnName,
                        ResultColumn = capturedColumnInfo.ResultColumn,
                        ForceToUtc = capturedColumnInfo.ForceToUtc,
                        ComputedColumn = capturedColumnInfo.ComputedColumn,
                        ComputedColumnType = capturedColumnInfo.ComputedColumnType,
                        ColumnType = capturedColumnInfo.ColumnType,
                        ColumnAlias = capturedColumnInfo.ColumnAlias,
                        VersionColumn = capturedColumnInfo.VersionColumn,
                        VersionColumnType = capturedColumnInfo.VersionColumnType,
                        SerializedColumn = capturedColumnInfo.SerializedColumn
                    };

                    pc.SetMemberAccessors(accessors);

                    var childrenTableInfo = childTableInfoPlan == null ? tableInfo : childTableInfoPlan();
                    var children = childrenPlans.Select(plan => plan(childrenTableInfo)).ToList();

                    // Cascade ResultColumn down
                    foreach (var child in children.Where(child => child.PocoColumn != null && pc.ResultColumn))
                    {
                        child.PocoColumn.ResultColumn = true;
                    }

                    var pocoMember = new PocoMember()
                    {
                        MemberInfoData = memberInfoData,
                        MemberInfoChain = members,
                        IsList = isList,
                        IsDynamic = isDynamic,
                        PocoColumn = capturedColumnInfo.ComplexMapping ? null : pc,
                        ReferenceType = capturedColumnInfo.ReferenceType,
                        ReferenceMemberName = capturedColumnInfo.ReferenceMemberName,
                        PocoMemberChildren = children,
                    };

                    pocoMember.SetMemberAccessor(accessors[accessors.Count - 1], fastCreate, listType);

                    return pocoMember;
                });
            }
        }
コード例 #18
0
        public void SqlTemplateArgs()
        {
            var mappers = new NPoco.MapperCollection {
                new NullableDateMapper()
            };
            var factory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, mappers).Init());

            var sqlContext   = new SqlContext(new SqlServerSyntaxProvider(Options.Create(new GlobalSettings())), DatabaseType.SQLCe, factory);
            var sqlTemplates = new SqlTemplates(sqlContext);

            const string sqlBase = "SELECT [zbThing1].[id] AS [Id], [zbThing1].[name] AS [Name] FROM [zbThing1] WHERE ";

            SqlTemplate template = sqlTemplates.Get("sql1", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                                    .Where <Thing1Dto>(x => x.Name == SqlTemplate.Arg <string>("value")));

            Sql <ISqlContext> sql = template.Sql("foo");

            Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);

            sql = template.Sql(123);
            Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual(123, sql.Arguments[0]);

            template = sqlTemplates.Get("sql2", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .Where <Thing1Dto>(x => x.Name == SqlTemplate.Arg <string>("value")));

            sql = template.Sql(new { value = "foo" });
            Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);

            sql = template.Sql(new { value = 123 });
            Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual(123, sql.Arguments[0]);

            Assert.Throws <InvalidOperationException>(() => template.Sql(new { xvalue = 123 }));
            Assert.Throws <InvalidOperationException>(() => template.Sql(new { value = 123, xvalue = 456 }));

            var i = 666;

            template = sqlTemplates.Get("sql3", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .Where <Thing1Dto>(x => x.Id == i));

            sql = template.Sql("foo");
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);

            sql = template.Sql(123);
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual(123, sql.Arguments[0]);

            // but we cannot name them, because the arg name is the value of "i"
            // so we have to explicitely create the argument
            template = sqlTemplates.Get("sql4", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .Where <Thing1Dto>(x => x.Id == SqlTemplate.Arg <int>("i")));

            sql = template.Sql("foo");
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);

            sql = template.Sql(123);
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual(123, sql.Arguments[0]);

            // and thanks to a patched visitor, this now works
            sql = template.Sql(new { i = "foo" });
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);

            sql = template.Sql(new { i = 123 });
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual(123, sql.Arguments[0]);

            Assert.Throws <InvalidOperationException>(() => template.Sql(new { j = 123 }));
            Assert.Throws <InvalidOperationException>(() => template.Sql(new { i = 123, j = 456 }));

            // now with more arguments
            template = sqlTemplates.Get("sql4a", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .Where <Thing1Dto>(x => x.Id == SqlTemplate.Arg <int>("i") && x.Name == SqlTemplate.Arg <string>("name")));
            sql = template.Sql(0, 1);
            Assert.AreEqual(sqlBase + "((([zbThing1].[id] = @0) AND ([zbThing1].[name] = @1)))", sql.SQL.NoCrLf());
            Assert.AreEqual(2, sql.Arguments.Length);
            Assert.AreEqual(0, sql.Arguments[0]);
            Assert.AreEqual(1, sql.Arguments[1]);

            template = sqlTemplates.Get("sql4b", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .Where <Thing1Dto>(x => x.Id == SqlTemplate.Arg <int>("i"))
                                        .Where <Thing1Dto>(x => x.Name == SqlTemplate.Arg <string>("name")));
            sql = template.Sql(0, 1);
            Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0)) AND (([zbThing1].[name] = @1))", sql.SQL.NoCrLf());
            Assert.AreEqual(2, sql.Arguments.Length);
            Assert.AreEqual(0, sql.Arguments[0]);
            Assert.AreEqual(1, sql.Arguments[1]);

            // works, magic
            template = sqlTemplates.Get("sql5", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .WhereIn <Thing1Dto>(x => x.Id, SqlTemplate.ArgIn <int>("i")));

            sql = template.Sql("foo");
            Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0))", sql.SQL.NoCrLf());
            Assert.AreEqual(1, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);

            sql = template.Sql(new[] { 1, 2, 3 });
            Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0,@1,@2))", sql.SQL.NoCrLf());
            Assert.AreEqual(3, sql.Arguments.Length);
            Assert.AreEqual(1, sql.Arguments[0]);
            Assert.AreEqual(2, sql.Arguments[1]);
            Assert.AreEqual(3, sql.Arguments[2]);

            template = sqlTemplates.Get("sql5a", s => s.Select <Thing1Dto>().From <Thing1Dto>()
                                        .WhereIn <Thing1Dto>(x => x.Id, SqlTemplate.ArgIn <int>("i"))
                                        .Where <Thing1Dto>(x => x.Name == SqlTemplate.Arg <string>("name")));

            sql = template.Sql("foo", "bar");
            Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0)) AND (([zbThing1].[name] = @1))", sql.SQL.NoCrLf());
            Assert.AreEqual(2, sql.Arguments.Length);
            Assert.AreEqual("foo", sql.Arguments[0]);
            Assert.AreEqual("bar", sql.Arguments[1]);

            sql = template.Sql(new[] { 1, 2, 3 }, "bar");
            Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0,@1,@2)) AND (([zbThing1].[name] = @3))", sql.SQL.NoCrLf());
            Assert.AreEqual(4, sql.Arguments.Length);
            Assert.AreEqual(1, sql.Arguments[0]);
            Assert.AreEqual(2, sql.Arguments[1]);
            Assert.AreEqual(3, sql.Arguments[2]);
            Assert.AreEqual("bar", sql.Arguments[3]);

            // note however that using WhereIn in a template means that the SQL is going
            // to be parsed and arguments are going to be expanded etc - it *may* be a better
            // idea to just add the WhereIn to a templated, immutable SQL template

            // more fun...
            template = sqlTemplates.Get("sql6", s => s.Select <Thing1Dto>().From <Thing1Dto>()

                                        // do NOT do this, this is NOT a visited expression
                                        //// .Append(" AND whatever=@0", SqlTemplate.Arg<string>("j"))

                                        // does not work anymore - due to proper TemplateArg
                                        //// instead, directly name the argument
                                        ////.Append("AND whatever=@0", "j")
                                        ////.Append("AND whatever=@0", "k")

                                        // instead, explicitely create the argument
                                        .Append("AND whatever=@0", SqlTemplate.Arg("j"))
                                        .Append("AND whatever=@0", SqlTemplate.Arg("k")));

            sql = template.Sql(new { j = new[] { 1, 2, 3 }, k = "oops" });
            Assert.AreEqual(sqlBase.TrimEnd("WHERE ") + "AND whatever=@0,@1,@2 AND whatever=@3", sql.SQL.NoCrLf());
            Assert.AreEqual(4, sql.Arguments.Length);
            Assert.AreEqual(1, sql.Arguments[0]);
            Assert.AreEqual(2, sql.Arguments[1]);
            Assert.AreEqual(3, sql.Arguments[2]);
            Assert.AreEqual("oops", sql.Arguments[3]);
        }
コード例 #19
0
 public FastCreate(Type type, MapperCollection mapperCollection)
 {
     _type             = type;
     _mapperCollection = mapperCollection;
 }
コード例 #20
0
 public PocoData(Type type, MapperCollection mapper, IFastCreate creator)
 {
     CreateDelegate = creator;
     Type           = type;
     Mapper         = mapper;
 }
コード例 #21
0
 public FastCreate(Type type, MapperCollection mapperCollection)
 {
     _type             = type;
     _mapperCollection = mapperCollection;
     CreateDelegate    = GetCreateDelegate();
 }
コード例 #22
0
 public DatabaseFactoryConfigOptions()
 {
     Mapper       = new MapperCollection();
     Interceptors = new List <IInterceptor>();
 }
コード例 #23
0
 public PocoData(Type type, MapperCollection mapper) : this()
 {
     Type   = type;
     Mapper = mapper;
 }
コード例 #24
0
 public PocoDataFactory(MapperCollection mapper)
 {
     _mapper = mapper;
 }