开发者

How Can I Get the Identity Column Value Associated with a SubSonic 3 LinqTemplate Insert?

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)
    {
        Dicti开发者_如何学Pythononary<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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜