开发者

entity framework - retrieve Ids created by savechanges

Apologies for asking a related question yesterday, but after some sleep I've simplified my question.

In the example below,I loop through the objectquery sourcetable and add rows to the Positions table. After adding all the new rows and saving the changes, the primary keys (integer identity column) are created.

foreach (var row in sourcetable)
        {
            var newpos = new Positions()
                {
                    Field1 = row.field,
                    Field2 = row.field2,
                    Field3 = row.field3开发者_StackOverflow社区

                };

        }

    Entities.savechanges

In EF 3.5 is it possible to access the list of all primary keys added by the above process? Say something similar to what can done using the output statement in T-sql.


Sure - what you need to do is hang on to a list of those entities you're about to save, and then inspect them after they've been saved:

List<Positions> _newItems = new List<Positions>();

foreach (var row in sourcetable)
{
    var newpos = new Positions()
    {
        Field1 = row.field,
        Field2 = row.field2,
        Field3 = row.field3

    };

    _newItems.Add(newpos);

}

Entities.SaveChanges();

foreach(Positions p in _newItems)
{
    Console.WriteLine("ID for new item is: {0}", p.ID);
}

After the items have been saved, their field representing the INT IDENTITY field should be updated automagically, by EF, without you doing anything more. Just inspect the field!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜