entity framework: 在创建新条目时检索到Id

huangapple go评论62阅读模式
英文:

entity framework: retrieve Id of new entry upon creation

问题

以下是翻译好的部分:

有没有一种方法可以在不明确要求的情况下获取最后创建的条目的ID?

我正在执行以下操作:

public async Task SaveItemAsync(tblUsers item) //change here
{
if (item == null) throw new ArgumentException(nameof(item));
await InitializeAsync();
if (item.Id == null)
{
try
{
await _table.InsertItemAsync(item);
}
catch (Exception e)
{
var message = e.Message;
}
}
else await _table.ReplaceItemAsync(item);
}

但没有返回任何内容,但在数据库中创建了一个带有ID的条目。

如何更改以便返回新条目的ID?

英文:

is there a way to get the id of the last entry created without asking for it specifically?

I am doing this:

 public async Task SaveItemAsync(tblUsers item) //change here
        {
            if (item == null) throw new ArgumentException(nameof(item));
            await InitializeAsync();
            if (item.Id == null)
            {
                try
                {
                    await _table.InsertItemAsync(item);
                }
                catch (Exception e)
                {
                    var message = e.Message;
                }
            }
            else await _table.ReplaceItemAsync(item);
        }

anod nothing is returned but an entry with a Id is created on the db.

How can I alter that so that the Id of the new entry is returned?

答案1

得分: 1

如果id是由数据库生成的,Entity Framework应该在插入的实体中填充它,即:

_ctx.Items.Add(item);
await _ctx.SaveChangesAsync();
var insertedId = item.Id;

P.S.

  • 可能你想使用类似item.Id == default的方式来检查id是否为空。

  • 考虑使用DbContext.UpdateDbSet.Update方法,它们会为您执行关键检查(请参阅备注部分)。

英文:

If id is database generated Entity Framework should fill it in the inserted entity, i.e.:

_ctx.Items.Add(item);
await _ctx.SaveChangesAsync();
var insertedId = item.Id;

P.S.

  • Possibly you might want to use something like item.Id == default to check if the id is empty.

  • Consider using DbContext.Update or DbSet.Update method which will perform key checking for you (see the Remarks section).

huangapple
  • 本文由 发表于 2023年5月17日 21:06:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76272446.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定