I am using SubSonic 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?

Was it helpful?


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...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top