ExecuteDictionary

BLToolkit.NET

Business Logic Toolkit for .NET www.bltoolkit.net
  ExecuteDictionary.cs
using System;
using System.Collections.Generic;

using NUnit.Framework;

using BLToolkit.Common;
using BLToolkit.Data;
using BLToolkit.Mapping;

namespace HowTo.Data
{
    using DataAccess;

    [TestFixture]
    public class ExecuteDictionary
    {
        // The dictionary key is built from an object field/property.
        //
        Dictionary<int, Person> GetPersonDictionary1()
        {
            using (DbManager db = new DbManager())
            {
                return db
                    .SetCommand("SELECT * FROM Person")
                    .ExecuteDictionary<int, Person>("ID");
            }
        }

        [Test]
        public void Test1()
        {
            Dictionary<int, Person> dic = GetPersonDictionary1();

            Assert.AreNotEqual(0, dic.Count);
        }

        // The dictionary key is built from a recordset field value ('@' prefix).
        //
        Dictionary<int, Person> GetPersonDictionary2()
        {
            using (DbManager db = new DbManager())
            {
                return db
                    .SetCommand("SELECT * FROM Person")
                    .ExecuteDictionary<int, Person>("@PersonID");
            }
        }

        [Test]
        public void Test2()
        {
            Dictionary<int, Person> dic = GetPersonDictionary2();

            Assert.AreNotEqual(0, dic.Count);
        }

        // Complex dictionary key.
        //
        Dictionary<CompoundValue, Person> GetPersonDictionary3()
        {
            using (DbManager db = new DbManager())
            {
                return db
                    .SetCommand("SELECT * FROM Person")
                    .ExecuteDictionary<Person>(new MapIndex("FirstName", "LastName"));
            }
        }

        [Test]
        public void Test3()
        {
            Dictionary<CompoundValue, Person> dic = GetPersonDictionary3();

            Assert.AreNotEqual(0, dic.Count);
        }
    }
}
Person.cs
using System;

using BLToolkit.DataAccess;
using BLToolkit.Mapping;

namespace HowTo.DataAccess
{
    public class Person
    {
        [MapField("PersonID"), PrimaryKey, NonUpdatable]
        public int    ID;

        public string LastName;
        public string FirstName;
        public string MiddleName;
        public Gender Gender;
    }
}
Gender.cs
using System;

using BLToolkit.Mapping;

namespace HowTo.DataAccess
{
    public enum Gender
    {
        [MapValue("F")] Female,
        [MapValue("M")] Male,
        [MapValue("U")] Unknown,
        [MapValue("O")] Other
    }
}
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add
            key   = "ConnectionString"
            value = "Server=.;Database=BLToolkitData;Integrated Security=SSPI"/>
    </appSettings>
</configuration>
Create.sql script
 
© 2010 www.bltoolkit.net
[email protected]