views:

39

answers:

1

How can I get the Id back to the object when I'm using the AddMany function with SubSonic SimpleRepository. All my objects still get Id=0 when after using it.

SimpleRepository repository = new SimpleRepository(ConnectionStringName);
repository.AddMany<T>(insertList);

When looking at the source I can see that:

public void AddMany<T>(IEnumerable<T> items) where T : class, new()
{
    if (_options.Contains(SimpleRepositoryOptions.RunMigrations))
    {
        Migrate<T>();
    }

    BatchQuery batch = new BatchQuery(_provider);
    foreach(var item in items)
    {
        batch.QueueForTransaction(item.ToInsertQuery(_provider));
    }

    batch.ExecuteTransaction();
}

How about making a batch select for latest inserted Id in that table here? Could that ever return the wrong Id? I will write down some code and come back :)

The actual problem

The problem is that I like to use the inserted Id's in another row (different table) as a fk, maybe there is a way to use batch insert to add two different kinds of rows and set the fk-column to the last inserted id of the other row. A bit complicated there, but I think you get the point:

Insert User 
Insert UserAccount -> Set UserAccount.fk_UserId to latest id inserted in User
Insert User 
Insert UserAccount -> Set UserAccount.fk_UserId to latest id inserted in User

And so on as a batch.. is that possible? This could be as much as 10k or more rows times 2.

A: 

Ok, so I solved the actual problem:

IDataProvider provider = ProviderFactory.GetProvider(connectionStringName);

LogEntry entry1 = CreateEntry("1");
LogEntry entry2 = CreateEntry("2");
LogEntry entry3 = CreateEntry("3");
LogEntry entry4 = CreateEntry("4");

List<LogEntry> items = new List<LogEntry>() { entry1, entry2 };

BatchQuery batch = new BatchQuery();
foreach (var item in items)
{
    QueryCommand cmd = item.ToInsertQuery(provider).GetCommand();
    if (item != items.First())
    {
        cmd.CommandSql = cmd.CommandSql.Replace("@ins_LogEntriesfk_LogEntryId", "@@IDENTITY");
    }
    batch.QueueForTransaction(cmd);
}

batch.ExecuteTransaction();

Is this a prefered way on solving the problem. I got another idea, to store all id that's inserted in a table with a GroupId (Guid) and then extract this. There have to be an easier way to extract all inserted Ids on a connection?

Andreas