Stormy supports tables with an autonumber field. At insertion the object can automatically set its ID to the new auto-numbered value. The sample below shows how that can be done.

The used table is created by the program itself.

using System;
using System.Collections.Generic;

using System.Linq;
using System.Data;
using System.Data.SqlClient;

using Stormy;

namespace QuickStartAutoNumber
{
    // Model:
    public class Cat
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    // ORM Converter:
    public class CatConverter : ISelectable<Cat>, IInsertable<Cat>, 
                IAutoNumberable<Cat>
    {
        public Cat ApplySelect(IDataReader reader)
        {
            return new Cat()
                { 
                    Id = (int)reader["id"], 
                    Name = (string)reader["name"] 
                };
        }

        public string InsertSql()
        {
            return "insert into cats_an(name) values(@name)"; 
        }

        public void ApplyInsert(Cat cat, IDbCommand command)
        {
            var par = command.CreateParameter();
            par.ParameterName = "@name";
            par.DbType = DbType.String;
            par.Value = cat.Name;
            command.Parameters.Add(par);
        }

        public void ApplyAutoNumber(Cat cat, int newId)
        {
            cat.Id = newId;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Orm.Register<Cat>(new CatConverter());

            Connection connection = new Connection(new SqlConnection(
                    @"
                        Data Source=localhost\SQLEXPRESS;
                        MultipleActiveResultSets=True; 
                        Initial Catalog=stormy;
                        Integrated Security=SSPI;
                    "));

            // Create table (if it exists, we get a message but we ignore that)
            try
            {
                connection.Execute(
    "create table cats_an(id int identity primary key, name nvarchar(255))");
            }
            catch(Exception ex) 
            {
                if (!ex.Message.StartsWith("There is already an object named"))
                {
                    Console.WriteLine(ex.Message);
                }
            }

            // Create new cats
            var Tom = new Cat() { Name = "Tom" };
            var Jerry = new Cat() { Name = "Jerry" };

            // Insert these cats using the mapper defined above
            connection.Insert(Tom);
            connection.Insert(Jerry);

            // And they have auto-numbered ID's
            Console.WriteLine("Tom: id={0}, Jerry: id={1}", Tom.Id, Jerry.Id);

            var cats = connection.Select<Cat>("select * from cats_an");
            Console.WriteLine(String.Format("{0} cats available", cats.Count()));
        }
    }
}

Last edited Jan 1, 2012 at 10:48 PM by barendgehrels, version 5

Comments

No comments yet.