PrimaryKey

BLToolkit.NET

Business Logic Toolkit for .NET www.bltoolkit.net
 

The PrimaryKey attribute indicates the field that is a part of a primary key.

PrimaryKey.cs
using System;

using NUnit.Framework;

using BLToolkit.DataAccess;
using BLToolkit.Mapping;

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

            public string LastName;
            public string FirstName;
            public string MiddleName;
        }

        [Test]
        public void Test()
        {
            SqlQuery<Person> da = new SqlQuery<Person>();

            Person person = da.SelectByKey(1);

            Assert.IsNotNull(person);
        }
    }
}
DataAccessor.SelectByKeySql method generates and executes the following SQL statement:
SELECT
    [MiddleName],
    [PersonID],
    [LastName],
    [FirstName]
FROM
    [Person]
WHERE
    [PersonID] = @PersonID
MultiplePrimaryKey.cs
using System;

using NUnit.Framework;

using BLToolkit.DataAccess;
using BLToolkit.Mapping;

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

            // These fields are not real primary key of the table.
            // They are made primary key for demonstration purpose only.
            //
            [PrimaryKey(1)] public string FirstName;
            [PrimaryKey(2)] public string LastName;

            public string MiddleName;
        }

        [Test]
        public void Test()
        {
            SqlQuery<Person> query = new SqlQuery<Person>();

            Person person = query.SelectByKey("Tester", "Testerson");

            Assert.IsNotNull(person);
        }
    }
}
In this case DataAccessor.SelectByKeySql method generates and executes the following SQL statement:
SELECT
    [MiddleName],
    [PersonID],
    [LastName],
    [FirstName]
FROM
    [Person]
WHERE
    [FirstName] = @FirstName AND
    [LastName] = @LastName
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]