views:

176

answers:

1

I am using SubSonic 3.0.0.3 along with the Linq T4 Templates. My ProjectRepository, for example, has the following two methods:

public int Add(Project item)
{
    int result = 0;
    ISqlQuery query = BuildInsertQuery(item);

    if (query != null)
    {
       result = query.Execute();
    }
    return result;
}

private ISqlQuery BuildInsertQuery(Project item)
{
    ITable tbl = FindTableByClassName();

    Insert query = null;
    if (tbl != null)
    {
        Dictionary<string, object> hashed = item.ToDictionary();
        query = new Insert(_db.Provider).Into<Project>(tbl);

        foreach (string key in hashed.Keys)
        {
            IColumn col = tbl.GetColumn(key);
            if (col != null)
            {
                if (!col.AutoIncrement)
                {
                    query.Value(key, hashed[key]);
                }
            }
        }
    }

    return query;
}

Along with performing the insert (which works great), I'd really like to get the value of the auto-incrementing ProjectId column. For the record, this column is both the primary key and identity column. Is there perhaps a way to append "SELECT SCOPE_IDENTITY();" to the query or maybe there's an entirely different approach which I should try?

+3  A: 

You can do this with the ActiveRecord templates which does all of the wiring above for you (and also has built-in testing). In your scenario, the Add method would have one line: Project.Add() and it would return the new id.

For your needs, you can try this:

var cmd=query.GetCommand();
cmd.CommandSql+=";SELECT SCOPE_IDENTITY() as newid";
var newID=query.Provider.ExecuteScalar(cmd);

That should work..

*Edit - you can create an ExtensionMethod for this on ISqlQuery too, to save some writing...

Rob Conery
Thanks Rob. That did the trick. Prior to SubSonic 3 being shipped, I was using ActiveRecord with SubSonic 2.2 and liked it a lot but I thought I'd give the Linq Templates a try for this project. I've been really happy with the new templates so far. Thanks again for the helping hand you've offered here.
Ben Griswold