当前位置: 首页>>代码示例>>C#>>正文


C# Database.Select方法代码示例

本文整理汇总了C#中Database.Select方法的典型用法代码示例。如果您正苦于以下问题:C# Database.Select方法的具体用法?C# Database.Select怎么用?C# Database.Select使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Database的用法示例。


在下文中一共展示了Database.Select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: MainWindow

 public MainWindow()
 {
     InitializeComponent();
     db_connection = new  Database();
     question_list = db_connection.Select();
     foreach (Question i in question_list)
     { listBox.Items.Add(i); }
     main_game = new Game();
     main_game.startServerConenction();
 }
开发者ID:Tiesnesis,项目名称:VeA_Tasks,代码行数:10,代码来源:MainWindow.xaml.cs

示例2: Login

 public static UserObj Login(Database db, String username, String password)
 {
     DataSet data = db.Select("*", "Users", USERNAME + " = '" + username + "' AND " + PASSWORD + " = '" + password + "'");
     if (data.NumberOfRows() > 0)
     {
         return new UserObj(data);
     }
     else
     {
         return null;
     }
 }
开发者ID:phillipCouto,项目名称:Clear-Choice,代码行数:12,代码来源:UserObj.cs

示例3: DatabaseDeletesFirstLastWithActiveTransactions

        public void DatabaseDeletesFirstLastWithActiveTransactions()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();

            var objs = TestResourceFactory.GetMockClassAObjects(100).ToList();
            var ids = new List<int>();

            using (var fLock = new ManagedFileLock(_testName))
            {
                Cleanup();

                using (var db = new Database<int, MockClassA>(_testName + ".database", "Id", new FileCore<int, long>(), new BinConverter32(), new JSONFormatter()))
                {
                    db.Load();

                    var t = db.BeginTransaction();

                    objs.ToList().ForEach(o => ids.Add(db.Add(o)));

                    var last = db.SelectLast(s => true, 1).LastOrDefault();

                    Assert.IsNotNull(last);

                    var count = db.Update(s => s.Value<string>("Name") == last.Name
                        , new System.Action<MockClassA>(a => a.Name = "last"));

                    Assert.AreEqual(1, count);

                    var selected = db.Select(s => true);

                    Assert.AreEqual(100, selected.Count);

                    count = db.DeleteFirst(s => true, 10);

                    Assert.AreEqual(10, count);

                    selected = db.Select(s => true);

                    Assert.AreEqual(90, selected.Count);

                    count = db.DeleteLast(s => true, 10);

                    Assert.AreEqual(10, count);

                    selected = db.Select(s => true);

                    Assert.AreEqual(80, selected.Count);

                    t.Rollback();

                }
            }
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:53,代码来源:DatabaseQueryTests.cs

示例4: LotExtra

 public LotExtra(Database db)
     : base(Table, db)
 {
     PrimaryKeyColumns = new String[1] { PrimaryKey };
     Boolean tryAgain = true;
     String hashedKey = null;
     while (tryAgain)
     {
         hashedKey = "" + DateTime.Now.Ticks;
         DataSet res = db.Select(PrimaryKey, Table, PrimaryKey + " = '" + hashedKey + "'");
         if (res.NumberOfRows() == 0)
         {
             tryAgain = false;
         }
     }
     SetValue(PrimaryKey, hashedKey);
 }
开发者ID:phillipCouto,项目名称:Clear-Choice,代码行数:17,代码来源:LotExtra.cs

示例5: UserObj

 /// <summary>
 /// Creates a new User object with a fresh ACL
 /// </summary>
 /// <param name="db"></param>
 public UserObj(Database db)
     : base("Users", db)
 {
     //Set the unqiue ID column for the Object
     uniqueIDColumn = UID;
     //Generate random number for primary Key
     Random ranNum = new Random();
     Boolean tryAgain = true;
     int id = 0;
     while (tryAgain)
     {
         id = ranNum.Next(Int32.MaxValue);
         DataSet res = db.Select(uniqueIDColumn, "Users", uniqueIDColumn + " = " + id);
         if (res.NumberOfRows() == 0)
         {
             tryAgain = false;
         }
     }
     SetValue(uniqueIDColumn, id);
     AccessControlList = new ACS();
 }
开发者ID:phillipCouto,项目名称:Clear-Choice,代码行数:25,代码来源:UserObj.cs

示例6: Lot

 /// <summary>
 /// Creates a new Lot object using a the lot Table schema.
 /// </summary>
 /// <param name="table"></param>
 /// <param name="db"></param>
 public Lot(Database db)
     : base(Table, db)
 {
     PrimaryKeyColumns = new String[1]{PrimaryKey};
     //Generate random number for primary Key
     Random ranNum = new Random();
     Boolean tryAgain = true;
     int id = 0;
     String hashedKey = null;
     while (tryAgain)
     {
         id = ranNum.Next(10);
         String textKey = Table + ":" + DateTime.Now.Ticks + ":" + id;
         hashedKey = db.GetMD5Hash(textKey);
         DataSet res = db.Select(PrimaryKey, Table, PrimaryKey + " = '" + hashedKey + "'");
         if (res.NumberOfRows() == 0)
         {
             tryAgain = false;
         }
     }
     SetValue(PrimaryKey, hashedKey);
 }
开发者ID:phillipCouto,项目名称:Clear-Choice,代码行数:27,代码来源:Lot.cs

示例7: FullEnlistmentScopeCommitsTest

        public void FullEnlistmentScopeCommitsTest()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();

            var objects = TestResourceFactory.GetMockClassAObjects(12);

            ITransaction trans = null;

            using (var fLock = new ManagedFileLock(_testName))
            {
                Cleanup();

                using (var db = new Database<int, MockClassA>(_testName + ".database", "Id", new FileCore<int, long>(), new BinConverter32(), new BSONFormatter(),
                    new TransactionManager<int, MockClassA>() { DistributedScopeEnlistment = TransactionEnlistmentType.FullEnlistmentNotification }))
                {
                    db.Load();

                    using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew))
                    {
                        trans = db.BeginTransaction();

                        foreach (var obj in objects)
                            obj.Id = db.AddOrUpdate(obj, 0);

                        var update = db.Fetch(3);

                        update.Name = "Updated " + update.Id;

                        db.AddOrUpdate(update, update.Id);

                        db.Delete(objects.Last().Id);

                        scope.Complete();
                    }

                    while (!trans.IsComplete)
                        Thread.Sleep(100);
                }

                using (var db = new Database<int, MockClassA>(_testName + ".database", "Id", new FileCore<int, long>(), new BinConverter32(), new BSONFormatter(),
                    new TransactionManager<int, MockClassA>() { DistributedScopeEnlistment = TransactionEnlistmentType.FullEnlistmentNotification }))
                {
                    db.Load();

                    using (var scope = new System.Transactions.TransactionScope(TransactionScopeOption.RequiresNew))
                    {
                        trans = db.BeginTransaction();

                        db.Update<MockClassA>(u => !u.Value<string>("Name").Contains("Updated"), m => m.Name = "batch " + m.Id);

                        var old = db.Select(s => s.Value<string>("Name").Contains("Updated"));

                        Assert.AreEqual(1, old.Count);
                        Assert.AreEqual("Updated 3", old.Single().Name);

                        var updates = db.SelectFirst(s => s.Value<string>("Name").Contains("batch"), 11);

                        Assert.AreEqual(10, updates.Count);
                        Assert.AreEqual(1, updates.First().Id);
                        Assert.AreEqual(11, updates.Last().Id);

                        scope.Complete();
                    }

                    while (!trans.IsComplete)
                        Thread.Sleep(100);
                }
            }
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:69,代码来源:TransactionScopeTests.cs

示例8: Main

    public static void Main(String[] args) 
    { 
        Storage storage = StorageFactory.Instance.CreateStorage(); 
        storage.Open("testcodegenerator.dbs");
        Database db = new Database(storage);

        DateTime start = DateTime.Now;

        for (int i = 0; i < nLabels; i++) 
        { 
            RecordLabel label = new RecordLabel();
            label.name = "Label" + i;
            label.email = "[email protected]" + label.name + ".com";
            label.address = "Country, City, Street";
            label.phone = "+1 123-456-7890";
            db.AddRecord(label);
        }        

        for (int i = 0; i < nAlbums; i++) 
        { 
            Album album = new Album();
            album.name = "Album" + i;
            album.label = (RecordLabel)Enumerable.First(db.Select(typeof(RecordLabel), "name='Label" + (i % nLabels) + "'"));
            album.genre = "Rock";
            album.release = DateTime.Now;
            db.AddRecord(album);
            
            for (int j = 0; j < nTracksPerAlbum; j++) 
            { 
                Track track = new Track();
                track.no = j+1;
                track.name = "Track" + j;
                track.album = album;
                track.duration = 3.5f;
                db.AddRecord(track);                
            }
        }

        Console.WriteLine("Elapsed time for database initialization: " + (DateTime.Now - start));

        QueryExecutionListener listener = new QueryExecutionListener();
        storage.Listener = listener;

        Query trackQuery = db.CreateQuery(typeof(Track));
        CodeGenerator code = trackQuery.GetCodeGenerator();
        code.Predicate(code.And(code.Gt(code.Field("no"), 
                                        code.Literal(0)), 
                                code.Eq(code.Field(code.Field(code.Field("album"), "label"), "name"),
                                        code.Parameter(1, typeof(string)))));
        start = DateTime.Now;
        int nTracks = 0;
        for (int i = 0; i < nLabels; i++) 
        {
            trackQuery[1] = "Label" + i;
            foreach (Track t in trackQuery) 
            { 
                nTracks += 1;
            }
        }
        Console.WriteLine("Elapsed time for searching of " + nTracks + " tracks: " + (DateTime.Now - start));
        Debug.Assert(nTracks == nAlbums*nTracksPerAlbum);

        String prev = "";
        int n = 0;
        Query labelQuery = db.CreateQuery(typeof(RecordLabel));
        code = labelQuery.GetCodeGenerator();
        code.OrderBy("name");
        foreach (RecordLabel label in labelQuery)
        {
            Debug.Assert(prev.CompareTo(label.name) < 0);
            prev = label.name;
            n += 1;
        }
        Debug.Assert(n == nLabels);

        prev = "";
        n = 0;
        code = labelQuery.GetCodeGenerator();
        code.Predicate(code.Like(code.Field("name"), 
                                 code.Literal("Label%")));
        code.OrderBy("name");
        foreach (RecordLabel label in labelQuery)
        {
            Debug.Assert(prev.CompareTo(label.name) < 0);
            prev = label.name;
            n += 1;
        }
        Debug.Assert(n == nLabels);

        n = 0;
        code = labelQuery.GetCodeGenerator();
        code.Predicate(code.In(code.Field("name"), 
                               code.List(code.Literal("Label1"), code.Literal("Label2"), code.Literal("Label3"))));
        foreach (RecordLabel label in labelQuery)
        {
            n += 1;
        }
        Debug.Assert(n == 3);

        n = 0;
//.........这里部分代码省略.........
开发者ID:yan122725529,项目名称:TripRobot.Crawler,代码行数:101,代码来源:TestCodeGenerator.cs

示例9: GetLotService

 /// <summary>
 /// Returns a LotService that matches the referenced type.
 /// </summary>
 /// <param name="db"></param>
 /// <param name="service"></param>
 /// <returns></returns>
 public LotService GetLotService(Database db, LotServices service)
 {
     int serviceNum = 0;
     switch (service)
     {
         case LotServices.RoughIn:
             serviceNum = 0;
             break;
         case LotServices.Service:
             serviceNum = 1;
             break;
         case LotServices.Final:
             serviceNum = 2;
             break;
     }
     DataSet serviceData = db.Select("*", LotService.Table, LotService.Fields.lotID.ToString() + " = '" + GetLotID() + "' AND " + LotService.Fields.ServiceType.ToString() + " = " + serviceNum);
     if (serviceData.NumberOfRows() > 0)
     {
         serviceData.Read();
         return new LotService(serviceData.GetRecordDataSet());
     }
     return null;
 }
开发者ID:phillipCouto,项目名称:Clear-Choice,代码行数:29,代码来源:Lot.cs

示例10: CryptoSavesLargeFiles

        public void CryptoSavesLargeFiles()
        {
            _testName = System.Reflection.MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();
            Cleanup();

            for (var i = 0; i <= 25; i++)
            {
                _key.AppendChar((char)(((i + 25763) * i * Math.PI) % char.MaxValue));
                _vec.AppendChar((char)(((i + 41359) * i * Math.PI) % char.MaxValue));
            }

            var objects = new List<ResourceContainer>()
            {
                new Mocks.MockImageContainer(testRes.Luna_DIFF) { Name = "Luna_DIFF"},
                new Mocks.MockImageContainer(testRes.Luna_MAT) { Name = "Luna_MAT"},
                new Mocks.MockImageContainer(testRes.Luna_NRM) { Name = "Luna_NRM"}
            };

            using (var db = new Database<string, ResourceContainer>
                (_testName + ".database", "Name", new FileCore<string, long>(new SeedString(255), new Seed64()),
                new BinConverterString(),
                new QueryCryptoFormatter(new RC2Crypto(_vec), new BSONFormatter(), _key)))
            {
                db.Load();

                using (var t = db.BeginTransaction())
                {
                    foreach (var o in objects)
                        o.Name = db.Add(o);

                    t.Commit();
                }
            }

            using (var db = new Database<string, ResourceContainer>
                (_testName + ".database", new QueryCryptoFormatter(new RC2Crypto(_vec), new BSONFormatter(), _key)))
            {
                db.Load();

                var diff = db.Fetch("Luna_DIFF");

                Assert.IsNotNull(diff);

                var list = db.Select(s => true);

                Assert.AreEqual(3, list.Count);
            }
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:48,代码来源:CryptoDatabaseTests.cs

示例11: Main

    public static void Main(String[] args) 
    { 
        Storage storage = StorageFactory.Instance.CreateStorage(); 
        storage.Open("testautoindices.dbs");
        Database db = new Database(storage);

        db.EnableAutoIndices = true;

        DateTime start = DateTime.Now;

        for (int i = 0; i < nLabels; i++) 
        { 
            RecordLabel label = new RecordLabel();
            label.name = "Label" + i;
            label.email = "[email protected]" + label.name + ".com";
            label.address = "Country, City, Street";
            label.phone = "+1 123-456-7890";
            db.AddRecord(label);
        }        

        for (int i = 0; i < nAlbums; i++) 
        { 
            Album album = new Album();
            album.name = "Album" + i;
            album.label = (RecordLabel)Enumerable.First(db.Select(typeof(RecordLabel), "name='Label" + (i % nLabels) + "'"));
            album.genre = "Rock";
            album.release = DateTime.Now;
            db.AddRecord(album);
            
            for (int j = 0; j < nTracksPerAlbum; j++) 
            { 
                Track track = new Track();
                track.no = j+1;
                track.name = "Track" + j;
                track.album = album;
                track.duration = 3.5f;
                db.AddRecord(track);                
            }
        }

        Console.WriteLine("Elapsed time for database initialization: " + (DateTime.Now - start));

        QueryExecutionListener listener = new QueryExecutionListener();
        storage.Listener = listener;

        Query query = db.Prepare(typeof(Track), "album.label.name=?");
        start = DateTime.Now;
        int nTracks = 0;
        for (int i = 0; i < nLabels; i++) 
        {
            query[1] = "Label" + i;
            foreach (Track t in query) 
            { 
                nTracks += 1;
            }
        }
        Console.WriteLine("Elapsed time for searching of " + nTracks + " tracks: " + (DateTime.Now - start));
        Debug.Assert(nTracks == nAlbums*nTracksPerAlbum);

        String prev = "";
        int n = 0;
        foreach (RecordLabel label in db.Select(typeof(RecordLabel), "order by name"))
        {
            Debug.Assert(prev.CompareTo(label.name) < 0);
            prev = label.name;
            n += 1;
        }
        Debug.Assert(n == nLabels);

        prev = "";
        n = 0;
        foreach (RecordLabel label in db.Select(typeof(RecordLabel), "name like 'Label%' order by name"))
        {
            Debug.Assert(prev.CompareTo(label.name) < 0);
            prev = label.name;
            n += 1;
        }
        Debug.Assert(n == nLabels);

        n = 0;
        foreach (RecordLabel label in db.Select(typeof(RecordLabel), "name in ('Label1', 'Label2', 'Label3')"))
        {
            n += 1;
        }
        Debug.Assert(n == 3);

        n = 0;
        foreach (RecordLabel label in db.Select(typeof(RecordLabel), "(name = 'Label1' or name = 'Label2' or name = 'Label3') and email like '[email protected]%'"))
        {
            n += 1;
        }
        Debug.Assert(n == 3);

        Query query2 = db.Prepare(typeof(RecordLabel), "phone like '+1%' and name in ?");
        ArrayList list = new ArrayList(nLabels);
        for (int i = 0; i < nLabels; i++) 
        {
            list.Add("Label" + i);
        }
        n = 0;
//.........这里部分代码省略.........
开发者ID:yan122725529,项目名称:TripRobot.Crawler,代码行数:101,代码来源:TestAutoIndices.cs

示例12: CryptoSerializesQueries

        public void CryptoSerializesQueries()
        {
            _testName = System.Reflection.MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();
            Cleanup();

            var key = new SecureString();
            var vec = new SecureString();

            for (var i = 0; i <= 25; i++)
            {
                key.AppendChar((char)(((i + 25763) * i * Math.PI) % char.MaxValue));
                vec.AppendChar((char)(((i + 41359) * i * Math.PI) % char.MaxValue));
            }

            var objects = new List<ResourceContainer>()
            {
                new Mocks.MockImageContainer(testRes.Luna_DIFF) { Name = "Luna_DIFF"},
                new Mocks.MockImageContainer(testRes.Luna_MAT) { Name = "Luna_MAT"},
                new Mocks.MockImageContainer(testRes.Luna_NRM) { Name = "Luna_NRM"}
            };

            using (var db = new Database<string, ResourceContainer>
                (_testName + ".database", "Name", new FileCore<string, long>(new SeedString(255), new Seed64()),
                new BinConverterString(),
                new QueryCryptoFormatter(new RC2Crypto(vec), new BSONFormatter(), key)))
            {
                db.Load();

                using (var t = db.BeginTransaction())
                {
                    foreach (var o in objects)
                        o.Name = db.Add(o);

                    t.Commit();
                }

                var dmm = DynamicMemberManager.GetManager(db);
                Assert.AreEqual(3, dmm._primaryIndex.Length);

                using (var t = db.BeginTransaction())
                {
                    foreach (var o in objects)
                        db.Update(o, o.Name);

                    t.Commit();
                }

                Assert.AreEqual(3, dmm._primaryIndex.Length);
            }

            using (var db = new Database<string, ResourceContainer>
                (_testName + ".database", new QueryCryptoFormatter(new RC2Crypto(vec), new BSONFormatter(), key)))
            {
                db.Load();

                using (var t = db.BeginTransaction())
                {
                    db.Delete("Luna_MAT");
                    t.Commit();
                }

                Assert.IsNull(db.Fetch("Luna_MAT"));

                var o = db.Select(s => true);

                Assert.AreEqual(2, o.Count);
            }
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:68,代码来源:CryptoDatabaseTests.cs

示例13: DatabaseAddsUpdatesAndQueriesActiveTransaction

        public void DatabaseAddsUpdatesAndQueriesActiveTransaction()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();
            Cleanup();

            var objects = TestResourceFactory.GetMockClassAObjects(12);

            using (var db = new Database<int, MockClassA>(_testName + ".database", "Id"))
            {
                db.Load();

                db.BeginTransaction();

                foreach (var obj in objects)
                    db.AddOrUpdate(obj, 0);

                var update = db.Fetch(3);

                update.Name = "Updated " + update.Id;

                db.AddOrUpdate(update, update.Id);

                db.FlushAll();
            }

            using (var db = new Database<int, MockClassA>(_testName + ".database"))
            {
                db.Load();

                db.Update<MockClassA>(u => !u.Value<string>("Name").Contains("Updated"), m => m.Name = "batch " + m.Id);

                db.FlushAll();

                var old = db.Select(s => s.Value<string>("Name").Contains("Updated"));

                Assert.AreEqual(1, old.Count);
                Assert.AreEqual("Updated 3", old.Single().Name);

                var updates = db.SelectFirst(s => s.Value<string>("Name").Contains("batch"), 11);

                Assert.AreEqual(11, updates.Count);
                Assert.AreEqual(1, updates.First().Id);
                Assert.AreEqual(12, updates.Last().Id);
            }
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:45,代码来源:DatabaseTransactionTests.cs

示例14: SaveObject

        /// <summary>
        /// Saves the Dataobject to the Database
        /// </summary>
        /// <param name="IndexColumn"></param>
        /// <param name="db"></param>
        public void SaveObject(Database db)
        {
            this.SetValue(LASTMODIFIED, DateTime.Now);
            this.SetValue(MODIFIEDBY, System.Environment.UserName);
            StringBuilder whereBuilder = new StringBuilder();
            bool first = true;
            foreach (String column in PrimaryKeyColumns)
            {
                if (!first)
                {
                    whereBuilder.Append(" AND ");
                }
                else
                {
                    first = false;
                }
                whereBuilder.Append("`" + column + "` = ");
                if (data.IsColumnNumberDataType(column))
                {
                    whereBuilder.Append(data.getString(column));
                }
                else
                {
                    whereBuilder.Append("'" + data.getString(column) + "'");
                }
            }
            if (newObject)
            {
                try
                {
                    db.Insert(data.GetTableName(), data);
                    newObject = false;
                    updates = new Hashtable();
                    //Parse an array of UniqueID Columns
                    StringBuilder description = new StringBuilder();
                    first = true;
                    foreach (String column in PrimaryKeyColumns)
                    {
                        if (!first)
                        {
                            description.Append(" and ");
                        }
                        else
                        {
                            first = false;
                        }
                        description.Append(column + " is " + data.getString(column));
                    }
                    //Submit an audit event
                    AuditEvent auditEvent = new AuditEvent(db);
                    auditEvent.EventDescription(data.GetTableName(), "New Object added, " + description.ToString());
                    auditEvent.SaveEvent();
                }
                catch (Exception e)
                {
                    Console.Write(e.StackTrace);
                    throw new Exception("Database Error, Audit log failed.", e);
                }
            }
            else
            {
                StringBuilder setStr = new StringBuilder();
                bool firstKey = true;
                foreach (Object key in updates.Keys)
                {
                    if (!firstKey)
                    {
                        setStr.Append(",");
                    }
                    else
                    {
                        firstKey = false;
                    }
                    setStr.Append("`" + key.ToString() + "` = ");
                    if (data.IsColumnNumberDataType(key.ToString()))
                    {
                        setStr.Append(updates[key].ToString());
                    }
                    else if (updates[key].Equals(DBNull.Value))
                    {
                        setStr.Append("NULL");
                    }
                    else
                    {
                        setStr.Append("'" + updates[key].ToString() + "'");
                    }
                }
                DataSet check = db.Select(LASTMODIFIED + "," + MODIFIEDBY, data.GetTableName(), whereBuilder.ToString());
                MessageBoxResult askBox;
                if (!check.getDateTime(LASTMODIFIED).Equals(data.getDateTime(LASTMODIFIED)))
                {
                    askBox = MessageBox.Show(data.GetTableName() + " Object has already been modified by " + check.getString(MODIFIEDBY) + " since you have opened this object. Continue with operation?", "Consistency Error", MessageBoxButton.YesNo, MessageBoxImage.Exclamation);
                    if (askBox == MessageBoxResult.Yes)
                    {
                        db.Update(data.GetTableName(), setStr.ToString(), whereBuilder.ToString());
//.........这里部分代码省略.........
开发者ID:phillipCouto,项目名称:Clear-Choice,代码行数:101,代码来源:DataObject.cs

示例15: DatabaseSavesOneHundredThousandRecords

        public void DatabaseSavesOneHundredThousandRecords()
        {
            _testName = MethodInfo.GetCurrentMethod().Name.GetHashCode().ToString();

            decimal avgTime = 0;
            var stopWatch = new Stopwatch();

            using (var fLock = new ManagedFileLock(_testName))
            {
                Cleanup();

                using (var db = new Database<int, MockClassA>(_testName + ".database", "Id"))
                {
                    db.Load();

                    stopWatch.Start();
                    using (var t = db.BeginTransaction())
                    {
                        TestResourceFactory.GetMockClassAObjects(25000).ToList().ForEach(a => db.Add(a));

                        t.Commit();
                    }
                    stopWatch.Stop();
                    avgTime = (avgTime + stopWatch.ElapsedMilliseconds);

                    Console.WriteLine("Transaction with 25000 entities committed in {0} seconds", stopWatch.ElapsedMilliseconds / 1000m);

                    stopWatch.Reset();
                    stopWatch.Start();
                    using (var t = db.BeginTransaction())
                    {
                        TestResourceFactory.GetMockClassAObjects(25000).ToList().ForEach(a => db.Add(a));

                        t.Commit();
                    }
                    stopWatch.Stop();
                    avgTime = (avgTime + stopWatch.ElapsedMilliseconds) / 2;

                    Console.WriteLine("Transaction with 25000 entities committed in {0} seconds", stopWatch.ElapsedMilliseconds / 1000m);

                    stopWatch.Reset();
                    stopWatch.Start();
                    using (var t = db.BeginTransaction())
                    {
                        TestResourceFactory.GetMockClassAObjects(25000).ToList().ForEach(a => db.Add(a));

                        t.Commit();
                    }
                    stopWatch.Stop();
                    avgTime = (avgTime + stopWatch.ElapsedMilliseconds) / 2;

                    Console.WriteLine("Transaction with 25000 entities committed in {0} seconds", stopWatch.ElapsedMilliseconds / 1000m);

                    stopWatch.Reset();
                    stopWatch.Start();
                    using (var t = db.BeginTransaction())
                    {
                        TestResourceFactory.GetMockClassAObjects(25000).ToList().ForEach(a => db.Add(a));

                        t.Commit();
                    }
                    stopWatch.Stop();
                    avgTime = (avgTime + stopWatch.ElapsedMilliseconds) / 2;

                    Console.WriteLine("Transaction with 25000 entities committed in {0} seconds", stopWatch.ElapsedMilliseconds / 1000m);

                    Console.WriteLine("Avg Commit time for trans with 25000 entities {0} seconds", avgTime / 1000m);

                    stopWatch.Reset();
                    stopWatch.Start();
                    Assert.AreEqual(20000, db.Select(o => o.Value<int>("Id") > 80000).Count());
                    stopWatch.Stop();

                    Console.WriteLine("query with 20000 records retreived in {0} seconds", stopWatch.ElapsedMilliseconds / 1000m);

                    db.Flush();
                }

                using (var db = new Database<int, MockClassA>(_testName + ".database"))
                {
                    var len = db.Load();

                    Assert.AreEqual(100000, len);

                    stopWatch.Reset();
                    stopWatch.Start();
                    Assert.AreEqual(20000, db.Select(o => o.Value<int>("Id") > 80000).Count());
                    stopWatch.Stop();

                    Console.WriteLine("query with 20000 records retreived in {0} seconds", stopWatch.ElapsedMilliseconds / 1000m);

                    db.Clear();
                }
            }
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:95,代码来源:DatabaseCapacityTests.cs


注:本文中的Database.Select方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。